diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 358479997..2bf156ed9 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -45,7 +45,7 @@ updates: - dependency-name: "monty-types" - dependency-name: "monty-macros" - # Crates only the two forks declare. The forks track Monty 1.4.0's own + # Crates only the two forks declare. The forks track Monty 1.5.0's own # dependency versions and move only when upstream source is re-copied; # a Dependabot bump edits the fork manifests directly (#2848 bumped # ruff_python_* 0.0.14 -> 0.0.20 and unicode_names2 1 -> 4, and failed @@ -56,7 +56,7 @@ updates: # there as well as in the workspace), which check_monty_fork.py rejects # unless the fork's line carries a `bashkit fork:` marker. So taking one # of those bumps means moving the fork line and marking it, not just the - # workspace line; fancy-regex and getrandom are marked that way today. + # workspace line; getrandom and jiter are marked that way today. # scripts/tests/test_dependabot_coverage.py keeps this list complete. - dependency-name: "ahash" - dependency-name: "hashbrown" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index be3b3650c..f332cc13c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,7 +70,7 @@ jobs: - name: Test repo scripts run: python3 -m unittest discover -s scripts/tests -p 'test_*.py' - # The Monty forks must match the pinned upstream 1.4.0 crates except + # The Monty forks must match the pinned upstream 1.5.0 crates except # where a `bashkit fork:` comment marks a local edit. - name: Check Monty fork drift run: python3 scripts/check_monty_fork.py diff --git a/Cargo.lock b/Cargo.lock index bf6005559..e42750e67 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -639,6 +639,7 @@ dependencies = [ "ruff_text_size", "serde", "serde_bytes", + "serde_json", "sha1", "sha2 0.11.1", "smallvec", @@ -656,6 +657,7 @@ dependencies = [ "chrono", "jiff", "monty-macros", + "nix", "num-bigint 0.4.8", "num-traits", "ruff_python_stdlib", @@ -1231,7 +1233,7 @@ version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2106,7 +2108,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3760,9 +3762,9 @@ dependencies = [ [[package]] name = "monty-macros" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb48631728d292ef4fd0eb58a7bbe65047fc70beef3c3659d0d3288a71a28f3c" +checksum = "42f92efd684a093a15b538139f8cc82a7c9c7c58fc2aa4733ecf32fd979e44ab" dependencies = [ "proc-macro2", "quote", @@ -5583,7 +5585,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5641,7 +5643,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -6517,10 +6519,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -6998,7 +7000,7 @@ version = "2.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5283634e518fe9e82c7b20520bb4bc209009fd16c82077c802f8111ecbb0117a" dependencies = [ - "rand 0.9.5", + "rand 0.10.3", ] [[package]] @@ -7670,7 +7672,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/README.md b/README.md index fe6d5675a..06ff0d62e 100644 --- a/README.md +++ b/README.md @@ -360,7 +360,7 @@ See [knowledge/integrations/git-support.md](knowledge/integrations/git-support.m ## Experimental: Python Support Enable the `python` feature to embed the [Monty](https://github.com/pydantic/monty) Python interpreter (pure Rust, Python 3.12). -Bashkit uses a slightly patched Monty 1.4, published as `bashkit-monty` and `bashkit-monty-types`: the patch adds a per-run memory probe and a VM checkpoint hook, so concurrent runs in one process get separate memory limits and honour cancellation. The upstream proposal is [pydantic/monty#740](https://github.com/pydantic/monty/pull/740); the forks go away once upstream has the hooks. +Bashkit uses a slightly patched Monty 1.5, published as `bashkit-monty` and `bashkit-monty-types`: the patch adds a per-run memory probe and a VM checkpoint hook, so concurrent runs in one process get separate memory limits and honour cancellation. The upstream proposal is [pydantic/monty#740](https://github.com/pydantic/monty/pull/740); the forks go away once upstream has the hooks. Python code runs in-memory with configurable resource limits and VFS bridging, files created by bash are readable from Python and vice versa. diff --git a/crates/bashkit-monty-types/Cargo.toml b/crates/bashkit-monty-types/Cargo.toml index 630516d7a..66550ffa5 100644 --- a/crates/bashkit-monty-types/Cargo.toml +++ b/crates/bashkit-monty-types/Cargo.toml @@ -1,11 +1,11 @@ -# Fork of pydantic/monty monty-types-1.4.0 (MIT) for bashkit's in-process Python. +# Fork of pydantic/monty monty-types-1.5.0 (MIT) for bashkit's in-process Python. # # Important decision (security): bashkit runs many tenants' Python in one # process. Upstream Monty enforces `max_memory` through a process-wide # allocator counter and has no in-VM host checkpoint, so bashkit carries a # small patch in `bashkit-monty-types` (`set_memory_probe`, pydantic/monty#740, # and `set_checkpoint_hook`) and republishes `monty` against it. Source is -# upstream monty-types-1.4.0 unchanged except marked edits; the library names stay `monty` / +# upstream monty-types-1.5.0 unchanged except marked edits; the library names stay `monty` / # `monty_types` so code reads as upstream. Drop both crates once upstream ships # the hooks. See knowledge/runtimes/python-builtin.md. # @@ -22,7 +22,7 @@ rust-version = "1.96" authors = ["Samuel Colvin ", "Everruns"] license = "MIT" repository.workspace = true -description = "Fork of pydantic/monty's monty-types 1.4.0 with an embedder memory probe and checkpoint hook, for bashkit's python3" +description = "Fork of pydantic/monty's monty-types 1.5.0 with an embedder memory probe and checkpoint hook, for bashkit's python3" keywords = ["python", "interpreter", "sandbox", "bashkit"] categories = ["compilers", "emulators"] readme = "README.md" @@ -38,7 +38,7 @@ doctest = false [dependencies] chrono = { version = "0.4", features = ["serde"] } jiff = { version = "0.2", features = ["std", "serde"], default-features = false } -monty-macros = { version = "1.4.0" } +monty-macros = { version = "=1.5.0" } num-bigint = { version = "0.4", features = ["serde"] } num-traits = { version = "0.2" } ruff_python_stdlib = { version = "0.0.14" } @@ -50,7 +50,11 @@ unicode-general-category = { version = "1" } [target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies] web-time = { version = "1.1" } +[target.'cfg(target_os = "linux")'.dependencies] +nix = { version = "0.31", features = ["fs", "time"], optional = true } + [features] +cpu-clock = ["dep:nix"] test-hooks = [] tzdb = ["jiff/tzdb-zoneinfo", "tzdb-bundled"] tzdb-bundled = ["jiff/tzdb-bundle-always"] diff --git a/crates/bashkit-monty-types/README.md b/crates/bashkit-monty-types/README.md index eeba357b6..509f382de 100644 --- a/crates/bashkit-monty-types/README.md +++ b/crates/bashkit-monty-types/README.md @@ -36,6 +36,10 @@ implementation**. ## Who should depend on it +The `monty` interpreter enables the `cpu-clock` feature for native CPU accounting, which is Linux-only. +Host-only users do not need this feature or its platform CPU dependencies. +`ExecutionClock::is_available()` reports whether the current thread can read the selected clock. + Host-side crates that need these types without linking the interpreter — `monty-fs` (which services `OsFunctionCall`s locally via `MountTable::handle_os_call`), `monty-pool` (which talks to Monty workers @@ -64,6 +68,19 @@ assert_eq!(value.py_repr(), "[1, 'x']"); - [`monty-typeshed`](https://crates.io/crates/monty-typeshed) — the trimmed typeshed stubs describing the stdlib subset Monty implements. - [`monty-macros`](https://crates.io/crates/monty-macros) — the proc macros behind `monty`'s argument parsing. +## Execution time + +Execution budgets charge bytecode and native builtins, excluding host suspension. +They use `ExecutionClock::Wall` by default. Native callers can select +`ExecutionClock::Cpu` with `ResourceTracker::with_execution_clock`. +Subprocess hosts set `PoolConfig::execution_clock` once for the pool; CPU enforcement needs a local Linux subprocess +worker, so remote (gRPC) setups enable it in the server's local pool. CPU mode samples the executing +thread with a cache of up to 1 ms and reads exact execution boundaries. +Unavailable or unusable counters use conservative elapsed time for that window; off Linux the counter is always +unavailable, so check `ExecutionClock::is_available()` before selecting CPU mode directly. +The OS controls counter accuracy and resolution. Snapshots preserve clock selection +and recorded consumption. WebAssembly workers accept wall mode only. + ## License MIT diff --git a/crates/bashkit-monty-types/src/import.rs b/crates/bashkit-monty-types/src/import.rs new file mode 100644 index 000000000..4a0ed9462 --- /dev/null +++ b/crates/bashkit-monty-types/src/import.rs @@ -0,0 +1,186 @@ +//! Imports the host resolves: the [`ImportArgs`] an +//! [`OsFunctionCall::Import`](crate::OsFunctionCall::Import) carries, and the +//! `.py` file search a host runs when it has no host module of that name. +//! +//! The sandbox never reads module files itself. It sends one `import` call per +//! module, and the host answers with a host module, a [`ModuleFile`] it found +//! on the search path, or not-found. [`find_module_file`] is the search, in +//! CPython's order; hosts supply how one candidate is read. + +use crate::{ + exceptions::{ExcType, MontyException}, + object::CallArgs, + results::ExtFunctionResult, + type_checking::is_identifier, +}; + +/// The most search-path directories an import searches; later ones are ignored. +/// +/// The sandbox sets `__path__`, and each directory costs the host two reads in +/// one suspension, so without a cap a long `__path__` amplifies host work. +pub const MAX_SEARCH_DIRS: usize = 32; + +/// The arguments of an `import` call: the module and where its file may be. +/// +/// Deserializes from a bare module name too, the form dumps written before +/// file imports store; such a call has an empty search path. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(from = "DumpedImportArgs")] +pub struct ImportArgs { + /// The fully-qualified dotted module name, e.g. `pkg.sub`. + pub module: String, + /// Absolute virtual directories to search for the module's file, in order: + /// the working directory for a top-level name, the package's `__path__` + /// for a submodule. Empty means the host offers host modules only. + pub search_path: Vec, +} + +impl ImportArgs { + /// An import of `module` that only host modules can answer. + #[must_use] + pub fn new(module: impl Into) -> Self { + Self { + module: module.into(), + search_path: Vec::new(), + } + } + + /// Reads the arguments back from the [`CallArgs`] a host sees for an + /// `import` call: the module name, then its search path, which a call from + /// a sandbox predating file imports leaves out. `None` when malformed. + #[must_use] + pub fn from_call_args(args: &CallArgs) -> Option { + let mut args = args.args(); + let module = args.next()?.as_str()?.to_owned(); + let search_path = match args.next() { + Some(dirs) => dirs + .items()? + .iter() + .map(|dir| dir.as_str().map(str::to_owned)) + .collect::>()?, + None => Vec::new(), + }; + args.next().is_none().then_some(Self { module, search_path }) + } + + /// The files that may hold the module, in the order a search reads them: + /// per directory, the package `name/__init__.py` before the module `name.py`. + /// + /// The call comes from an untrusted sandbox, so a name with a component + /// that is not an identifier has no candidates, and a directory that is not + /// absolute or holds a NUL byte is skipped, and only the first + /// [`MAX_SEARCH_DIRS`] remaining directories are searched. Paths are built one directory at + /// a time: a long name times many directories never sits in memory at once. + /// They are not normalized: mounts check them as sent, as for `open()`, and + /// an `os` handler receives them normalized through [`OsFunctionCall::to_args`](crate::OsFunctionCall::to_args). + pub fn candidates(&self) -> impl Iterator + '_ { + let valid = self.module.split('.').all(is_identifier); + let leaf = self.module.rsplit('.').next().unwrap_or(&self.module); + self.search_path + .iter() + .filter(move |dir| valid && dir.starts_with('/') && !dir.contains('\0')) + .take(MAX_SEARCH_DIRS) + .flat_map(move |dir| { + let dir = dir.strip_suffix('/').unwrap_or(dir); + [format!("{dir}/{leaf}/__init__.py"), format!("{dir}/{leaf}.py")] + }) + } +} + +/// The two forms an `import` call's arguments take in a dump. +#[derive(serde::Deserialize)] +#[serde(untagged)] +enum DumpedImportArgs { + /// A dump written before file imports: the module name alone. + Name(String), + Args { + module: String, + search_path: Vec, + }, +} + +impl From for ImportArgs { + fn from(dumped: DumpedImportArgs) -> Self { + match dumped { + DumpedImportArgs::Name(module) => Self::new(module), + DumpedImportArgs::Args { module, search_path } => Self { module, search_path }, + } + } +} + +/// A module's `.py` file found by the host, which the sandbox runs as the module. +/// +/// A `path` ending in `/__init__.py` makes the module a package. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct ModuleFile { + /// The virtual path the file was read from: the module's `__file__`. + pub path: String, + /// The file's text. + pub source: String, +} + +/// The outcome of reading one candidate file during a [`find_module_file`] search. +#[derive(Debug)] +pub enum ModuleRead { + /// The file's text: the search ends here. + Text(String), + /// No such file: the search moves on. + Missing, + /// No handler serves this path: the search moves on, as for a missing file. + NotHandled, + /// Reading failed for another reason: the import raises it. + Error(MontyException), +} + +impl ModuleRead { + /// Classifies a `Path.read_text` failure: missing, a directory in the way, + /// or a path outside anything the host serves moves on; anything else raises. + #[must_use] + pub fn from_exception(exc: MontyException) -> Self { + match exc.exc_type() { + ExcType::FileNotFoundError + | ExcType::NotADirectoryError + | ExcType::IsADirectoryError + | ExcType::PermissionError => Self::Missing, + _ => Self::Error(exc), + } + } + + /// Classifies a host handler's answer to `Path.read_text` for a candidate. + #[must_use] + pub fn from_result(result: ExtFunctionResult) -> Self { + match result { + ExtFunctionResult::Return(value) => match value.as_ref().as_str() { + Some(text) => Self::Text(text.to_owned()), + None => Self::Error(MontyException::new( + ExcType::RuntimeError, + Some(format!( + "invalid return type: Path.read_text for an import must return a str, not {}", + value.as_ref().type_name() + )), + )), + }, + ExtFunctionResult::Error(exc) => Self::from_exception(exc), + ExtFunctionResult::NotFound(_) => Self::NotHandled, + ExtFunctionResult::Future(_) | ExtFunctionResult::ModuleFile(_) => Self::Error(MontyException::new( + ExcType::RuntimeError, + Some("Path.read_text for an import must be answered with a str".to_owned()), + )), + } + } +} + +/// Searches `args`' candidates with `read`, returning the first file found as +/// a [`ExtFunctionResult::ModuleFile`], or the error a read raised. +/// +/// `None` when no candidate exists: the host answers the import with not-found. +pub fn find_module_file(args: &ImportArgs, mut read: impl FnMut(&str) -> ModuleRead) -> Option { + for path in args.candidates() { + match read(&path) { + ModuleRead::Text(source) => return Some(ExtFunctionResult::ModuleFile(ModuleFile { path, source })), + ModuleRead::Missing | ModuleRead::NotHandled => {} + ModuleRead::Error(exc) => return Some(ExtFunctionResult::Error(exc)), + } + } + None +} diff --git a/crates/bashkit-monty-types/src/lib.rs b/crates/bashkit-monty-types/src/lib.rs index 1441e5113..b9f5d9f3b 100644 --- a/crates/bashkit-monty-types/src/lib.rs +++ b/crates/bashkit-monty-types/src/lib.rs @@ -13,6 +13,7 @@ mod exceptions; mod file_mode; pub mod format; mod graph; +mod import; mod io; mod object; mod os; @@ -33,6 +34,7 @@ pub use crate::{ }, file_mode::FileMode, format::{FormatComplex, FormatFloat, StringRepr, bytes_repr, bytes_repr_fmt, string_repr_fmt, utf8_error_reason}, + import::{ImportArgs, MAX_SEARCH_DIRS, ModuleFile, ModuleRead, find_module_file}, io::{ COLLECT_STREAMS_ENTRY_OVERHEAD, CollectedStreams, DEFAULT_MAX_PRINT_COLLECT_BYTES, PrintStream, PrintWriter, PrintWriterCallback, check_print_collect_limit, @@ -43,16 +45,17 @@ pub use crate::{ MontyType, NamedValues, ObjectRef, unstable, }, os::{ - GetenvArgs, IMPORT_CALL, IMPORT_STUBS_CALL, IMPORT_STUBS_CALL_ID, MAX_SLEEP_SECONDS, MkdirCallArgs, MontyPath, - OpenCallArgs, OsFunctionCall, PathBytesDataArgs, PathStringDataArgs, RenameCallArgs, SleepError, TimeCaller, - UrandomArgs, dir_stat, file_stat, sleep_duration, sleep_duration_saturating, stat_result, symlink_stat, + GET_TYPE_HINTS_CALL, GetenvArgs, IMPORT_CALL, IMPORT_STUBS_CALL, IMPORT_STUBS_CALL_ID, MAX_SLEEP_SECONDS, + MkdirCallArgs, MontyPath, OpenCallArgs, OsFunctionCall, PathBytesDataArgs, PathStringDataArgs, RenameCallArgs, + SleepError, TimeCaller, TypeHintsTarget, UrandomArgs, dir_stat, file_stat, sleep_duration, + sleep_duration_saturating, stat_result, symlink_stat, }, os_policy::{ DateTimeSource, NamedZone, OsPolicy, ProcessTime, RandomSeed, RandomStart, SandboxTimeZone, SleepMode, UnknownTimeZone, ZoneConstants, local_wall_clock, unix_seconds, }, resource::{ - BASELINE_MEMORY, DEFAULT_GC_INTERVAL, DEFAULT_MAX_RECURSION_DEPTH, DEFAULT_MAX_SUSPENSIONS, + BASELINE_MEMORY, DEFAULT_GC_INTERVAL, DEFAULT_MAX_RECURSION_DEPTH, DEFAULT_MAX_SUSPENSIONS, ExecutionClock, LARGE_RESULT_THRESHOLD, LIVE_MEMORY, OOM_EXIT_CODE, ResourceError, ResourceLimits, ResourceTracker, TimeLimitScope, allocate_into_baseline, memory_limit_with_headroom, set_checkpoint_hook, set_memory_probe, // bashkit fork: hooks }, diff --git a/crates/bashkit-monty-types/src/os.rs b/crates/bashkit-monty-types/src/os.rs index 704b271e8..99387c9cb 100644 --- a/crates/bashkit-monty-types/src/os.rs +++ b/crates/bashkit-monty-types/src/os.rs @@ -17,9 +17,12 @@ use crate::{ file_mode::FileMode, format::StringRepr, graph::{MontyGraph, MontyNode, NodeId}, + import::ImportArgs, object::{CallArgs, MontyObject, MontyTimeZone}, + results::ExtFunctionResult, scan::ScanArgs, unstable::{self, PushValue}, + uuid::MontyUuid, virtual_path::normalize_virtual_path, }; // ============================================================================= @@ -32,6 +35,10 @@ pub const IMPORT_CALL: &str = "import"; /// [`OsFunctionCall::ImportStubs`]'s dispatch name, handled like [`IMPORT_CALL`]. pub const IMPORT_STUBS_CALL: &str = "import_stubs"; +/// [`OsFunctionCall::GetTypeHints`]'s dispatch name. Hosts answer it from the +/// functions and classes they sent, before other OS handlers. +pub const GET_TYPE_HINTS_CALL: &str = "typing.get_type_hints"; + /// Reserved pre-feed [`OsFunctionCall::ImportStubs`] ID, outside the interpreter's IDs counted from zero. pub const IMPORT_STUBS_CALL_ID: u32 = u32::MAX; @@ -163,16 +170,23 @@ pub enum OsFunctionCall { AsyncSystemSleep(Duration), // ---- Host modules ------------------------------------------------------ - /// Requests a missing module by top-level name. The host returns its value, an exception, - /// or `not_found` / `not_handled` to raise `ModuleNotFoundError`. - /// `from m import a` and `import m.sub` then load attributes from that value. + /// Requests a module the sandbox does not bundle: a top-level name, or a + /// submodule of a package imported from a file. The host returns a module + /// value, the module's [`ModuleFile`](crate::ModuleFile) from its search + /// path, an exception, or `not_found` / `not_handled` for `ModuleNotFoundError`. + /// A host module's own submodules are its attributes and are never requested. #[strum(serialize = "import")] // IMPORT_CALL - Import(String), + Import(ImportArgs), /// Requests stubs for previously unrequested top-level imports before type-checking a feed. /// The host returns a dict of dotted module paths to stub source (or `None`), /// or `not_found` / `not_handled` for no stubs. #[strum(serialize = "import_stubs")] // IMPORT_STUBS_CALL ImportStubs(Vec), + /// `typing.get_type_hints()` of a host function or host class. The host + /// answers with a dict of hints, which the call returns as is; a host + /// that does not handle it gives `{}`. + #[strum(serialize = "typing.get_type_hints")] // GET_TYPE_HINTS_CALL + GetTypeHints(TypeHintsTarget), } impl OsFunctionCall { @@ -236,8 +250,13 @@ impl OsFunctionCall { Self::Sleep(delay) | Self::SystemSleep(delay) | Self::AsyncSleep(delay) | Self::AsyncSystemSleep(delay) => { single_arg(MontyNode::Float(delay.as_secs_f64())) } - Self::Import(name) => single_arg(MontyObject::string(name)), + Self::Import(a) => { + let mut call = single_arg(MontyObject::string(a.module)); + call.push_arg(MontyObject::list(a.search_path.into_iter().map(MontyObject::string))); + call + } Self::ImportStubs(names) => single_arg(MontyObject::list(names.into_iter().map(MontyObject::string))), + Self::GetTypeHints(target) => target.to_args(), } } @@ -284,6 +303,16 @@ impl OsFunctionCall { } } + /// Whether either raw filesystem path is `''`. + /// + /// CPython fails every such call with `FileNotFoundError` (existence + /// predicates return `False`), so the interpreter answers it locally rather + /// than resolving `''` to the working directory and asking the host. + #[must_use] + pub fn has_empty_path(&self) -> bool { + self.fs_primary_path().is_some_and(str::is_empty) || self.rename_destination().is_some_and(str::is_empty) + } + /// CPython's `ValueError` message for a path containing a null byte. /// /// The wording is not uniform in CPython: it comes from whichever layer @@ -348,7 +377,8 @@ impl OsFunctionCall { | Self::AsyncSleep(_) | Self::AsyncSystemSleep(_) | Self::Import(_) - | Self::ImportStubs(_) => None, + | Self::ImportStubs(_) + | Self::GetTypeHints(_) => None, } } @@ -398,20 +428,33 @@ impl OsFunctionCall { | Self::AsyncSleep(_) | Self::AsyncSystemSleep(_) | Self::Import(_) - | Self::ImportStubs(_) => (None, None), + | Self::ImportStubs(_) + | Self::GetTypeHints(_) => (None, None), }; primary.into_iter().chain(dst) } + /// The answer when no handler accepted this call: `not_found` for an import, + /// which the sandbox raises as `ModuleNotFoundError`, no hints (`{}`) for + /// `get_type_hints`, else the [`on_no_handler`](Self::on_no_handler) exception. + #[must_use] + pub fn no_handler_result(&self) -> ExtFunctionResult { + match self { + Self::Import(_) => ExtFunctionResult::NotFound(IMPORT_CALL.to_owned()), + Self::GetTypeHints(_) => ExtFunctionResult::Return(MontyObject::dict([])), + _ => ExtFunctionResult::Error(self.on_no_handler()), + } + } + /// Exception to raise when no handler accepted this call: `PermissionError` /// for FS ops (with the path), `ModuleNotFoundError` for an import, /// `RuntimeError` for the other non-FS ops. #[must_use] pub fn on_no_handler(&self) -> MontyException { - if let Self::Import(name) = self { + if let Self::Import(a) = self { MontyException::new( ExcType::ModuleNotFoundError, - Some(format!("No module named {}", StringRepr(name))), + Some(format!("No module named {}", StringRepr(&a.module))), ) } else if let Some(path) = self.fs_primary_path() { let path = if path.is_empty() { @@ -516,6 +559,45 @@ fn single_arg(value: impl PushValue) -> CallArgs { // ============================================================================= // Args structs — per-variant payloads carried by `OsFunctionCall`. // ============================================================================= + +/// The host object an [`OsFunctionCall::GetTypeHints`] asks about. +/// +/// A host sees it as two positional args: `('function', name)` or +/// `('class', id)`, the id as a uuid string. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum TypeHintsTarget { + /// A host function, by the name the sandbox calls it with. + Function(String), + /// A host class, by the id of the `ClassType` it crossed as. + Class(MontyUuid), +} + +impl TypeHintsTarget { + /// The `(kind, name or id)` args a host callback receives. + fn to_args(&self) -> CallArgs { + let (kind, key) = match self { + Self::Function(name) => ("function", name.clone()), + Self::Class(id) => ("class", id.to_string()), + }; + let mut call = single_arg(MontyObject::string(kind)); + call.push_arg(MontyObject::string(key)); + call + } + + /// Reads the target back from the [`CallArgs`] a host sees; `None` when malformed. + #[must_use] + pub fn from_call_args(args: &CallArgs) -> Option { + let mut args = args.args(); + let kind = args.next()?.as_str()?; + let key = args.next()?.as_str()?; + let target = match kind { + "function" => Some(Self::Function(key.to_owned())), + "class" => MontyUuid::parse(key).map(Self::Class), + _ => None, + }; + target.filter(|_| args.next().is_none()) + } +} // // Each variant carries a struct that derives `ToArgs` for projection to // `CallArgs`. Zero-arg variants use empty structs so `to_args()` has no diff --git a/crates/bashkit-monty-types/src/resource.rs b/crates/bashkit-monty-types/src/resource.rs index 4e8973f58..33ed9188e 100644 --- a/crates/bashkit-monty-types/src/resource.rs +++ b/crates/bashkit-monty-types/src/resource.rs @@ -5,7 +5,7 @@ use std::hint; #[cfg(not(target_arch = "wasm32"))] use std::thread; -#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] +#[cfg(all(target_arch = "wasm32", not(target_os = "unknown")))] use std::time::Instant; use std::{ cell::Cell, @@ -18,14 +18,12 @@ use std::{ time::Duration, }; -// `std::time::Instant::now()` panics ("time not implemented on this platform") -// on `wasm32-unknown-unknown`, so any duration limit aborts there. Swap in -// `web_time::Instant` (a `performance.now()`-backed drop-in) only for that -// target; every other target (native, WASI) keeps std, so the `web-time` -// dependency is pulled in only where it's needed (see Cargo.toml). #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] use web_time::Instant; +mod execution_clock; +use execution_clock::ExecutionInstant; + /// Exit code a worker uses when it exceeded its memory limit or the allocator /// refused an allocation, so the parent can report `MemoryError` instead of an /// unclassifiable `SIGABRT`. @@ -167,6 +165,26 @@ impl fmt::Display for ResourceError { impl Error for ResourceError {} +/// Clock used for execution budgets and execution-time telemetry. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ExecutionClock { + /// Elapsed time while the interpreter executes, including descheduling. + #[default] + Wall, + /// Thread CPU time, Linux only. A failed native clock uses conservative elapsed time. + /// CPU accounting is approximate and does not bound response latency. + Cpu, +} + +impl ExecutionClock { + /// Whether this thread can read the selected clock. CPU reads require Linux and the `cpu-clock` feature. + #[must_use] + pub fn is_available(self) -> bool { + self == Self::Wall || execution_clock::thread_cpu().is_some() + } +} + /// Configuration for resource limits. /// /// The time/memory/GC limits are optional — set to `None` to disable — but @@ -178,13 +196,13 @@ impl Error for ResourceError {} /// custom limits with the builder pattern. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ResourceLimits { - /// Maximum execution time for a single feed (`feed_start`, `feed_run` or - /// `call_function`), summed over the turns it takes and excluding time - /// suspended on the host. Bounds one snippet, not the session. + /// Maximum execution time per feed (`feed_start`, `feed_run` or `call_function`), + /// summed across turns, excluding host suspension. Uses the tracker's clock + /// (wall time by default, or [`ExecutionClock::Cpu`]). Bounds a snippet, not the session. pub max_feed_duration: Option, /// Maximum execution time for a single host turn, reset at each feed and /// each resume. Bounds the stretch of sandbox code between two host round - /// trips, so a host can bound its own response time per call. + /// trips. Use a separate host deadline to bound elapsed response time. pub max_turn_duration: Option, /// Maximum allocator-backed memory in bytes. /// @@ -302,6 +320,9 @@ impl ResourceLimits { /// that budget rather than restarting from zero. #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct ResourceTracker { + /// Clock paired with the accumulated execution time. Legacy dumps use wall time. + #[serde(default)] + execution_clock: ExecutionClock, limits: ResourceLimits, /// Execution time accumulated by completed `on_execution_start`/`stop` /// windows. Bounds nothing — it is what [`elapsed`](Self::elapsed) reports @@ -321,7 +342,7 @@ pub struct ResourceTracker { /// idle. Never serialized — a snapshot is by definition taken while not /// executing. #[serde(skip)] - running_since: Cell>, + running_since: Cell>, /// Optional override applied on top of `limits.max_recursion_depth`. /// /// `None` (the default — also the value any pre-`test-hooks` snapshot @@ -347,8 +368,8 @@ impl Default for ResourceTracker { } impl ResourceTracker { - /// Tightens restored limits to the destination policy without resetting execution clocks. - /// A snapshot can retain stricter limits but cannot increase the destination's allowance. + /// Caps restored limits without resetting consumption or relaxing stricter saved limits. + /// Callers must check clock compatibility first. This retains the saved clock. pub fn tighten_limits(&mut self, ceiling: &ResourceLimits) { self.limits.max_memory = tighter_limit(self.limits.max_memory, ceiling.max_memory); self.limits.max_feed_duration = tighter_limit(self.limits.max_feed_duration, ceiling.max_feed_duration); @@ -374,6 +395,7 @@ impl ResourceTracker { #[must_use] pub fn new(limits: ResourceLimits) -> Self { Self { + execution_clock: ExecutionClock::Wall, limits, total_execution_time: Cell::new(Duration::ZERO), feed_execution_time: Cell::new(Duration::ZERO), @@ -384,6 +406,16 @@ impl ResourceTracker { } } + /// Selects the execution clock before the tracker starts running. + /// + /// Off Linux, CPU mode cannot read the thread counter and charges elapsed time instead; + /// check [`ExecutionClock::is_available`] first to refuse it. + #[must_use] + pub fn with_execution_clock(mut self, clock: ExecutionClock) -> Self { + self.execution_clock = clock; + self + } + /// Returns the live recursion ceiling: the override if one is in effect, /// otherwise the configured `max_recursion_depth`. #[inline] @@ -393,10 +425,8 @@ impl ResourceTracker { .unwrap_or(self.limits.max_recursion_depth) } - /// Returns the cumulative execution time: bytecode-execution wall time - /// accumulated across runs/feeds, excluding time suspended on the host - /// or idle between feeds. Includes the in-progress window if the VM is - /// currently executing. + /// Returns cumulative execution time using the configured clock, excluding + /// time suspended on the host or idle between feeds. Includes the running window. /// /// Nothing is bounded by this — it is reported to the host for telemetry. /// The budgets are [`feed_elapsed`](Self::feed_elapsed) and @@ -427,7 +457,18 @@ impl ResourceTracker { /// rather than two. #[inline] fn running_window(&self) -> Duration { - self.running_since.get().map_or(Duration::ZERO, |t| t.elapsed()) + let Some(mut window) = self.running_since.get() else { + return Duration::ZERO; + }; + let elapsed = window.elapsed(); + self.running_since.set(Some(window)); + elapsed + } + + /// Returns the clock saved with this tracker's accumulated consumption. + #[must_use] + pub fn execution_clock(&self) -> ExecutionClock { + self.execution_clock } /// Returns the configured per-feed execution time limit, if any. @@ -728,14 +769,22 @@ impl ResourceTracker { self.running_since.get().is_none(), "nested on_execution_start: VM-internal re-entry must use the raw run loop, not run_external" ); - self.running_since.set(Some(Instant::now())); + let remaining = [ + (self.limits.max_feed_duration, self.feed_execution_time.get()), + (self.limits.max_turn_duration, self.turn_execution_time.get()), + ] + .into_iter() + .filter_map(|(limit, used)| limit.map(|limit| limit.saturating_sub(used))) + .min(); + self.running_since + .set(Some(ExecutionInstant::now(self.execution_clock, remaining))); } /// Called when the VM leaves its execution loop — on completion, error, /// or suspension at an external call. See [`on_execution_start`](Self::on_execution_start). pub fn on_execution_stop(&self) { - if let Some(started) = self.running_since.take() { - let window = started.elapsed(); + if let Some(mut started) = self.running_since.take() { + let window = started.elapsed_at_stop(); for clock in [ &self.total_execution_time, &self.feed_execution_time, diff --git a/crates/bashkit-monty-types/src/resource/execution_clock.rs b/crates/bashkit-monty-types/src/resource/execution_clock.rs new file mode 100644 index 000000000..300e59a57 --- /dev/null +++ b/crates/bashkit-monty-types/src/resource/execution_clock.rs @@ -0,0 +1,100 @@ +//! Execution-window accounting with sampled thread CPU time and an elapsed-time fallback. + +#[cfg(target_os = "linux")] +use std::thread::{ThreadId, current}; +use std::time::Duration; +#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] +use std::time::Instant; + +#[cfg(all(feature = "cpu-clock", target_os = "linux"))] +use nix::{libc::CLOCK_THREAD_CPUTIME_ID, time::ClockId}; +#[cfg(all(target_arch = "wasm32", target_os = "unknown"))] +use web_time::Instant; + +use super::ExecutionClock; + +/// Maximum interval between cooperative CPU samples. Boundaries always read directly. +const SAMPLE_INTERVAL: Duration = Duration::from_millis(1); + +/// One synchronous VM window. Only accumulated durations survive serialization. +#[derive(Clone, Copy, Debug)] +pub(super) struct ExecutionInstant { + wall: Instant, + cpu: Option, + sampled_at: Instant, + sample_interval: Duration, + last_elapsed: Duration, + #[cfg(target_os = "linux")] + thread: Option, +} + +impl ExecutionInstant { + /// Capture a fresh baseline on the executing thread, including after a resume or restore. + pub(super) fn now(clock: ExecutionClock, remaining: Option) -> Self { + let cpu = (clock == ExecutionClock::Cpu).then(thread_cpu).flatten(); + let wall = Instant::now(); + Self { + wall, + cpu, + sampled_at: wall, + sample_interval: remaining.map_or(SAMPLE_INTERVAL, |budget| budget.min(SAMPLE_INTERVAL)), + last_elapsed: Duration::ZERO, + #[cfg(target_os = "linux")] + thread: cpu.map(|_| current().id()), + } + } + + /// Reuse this window's sample until its polling interval expires. + pub(super) fn elapsed(&mut self) -> Duration { + self.measure(false) + } + + /// Include work since the last cooperative sample when the VM returns to its host. + pub(super) fn elapsed_at_stop(&mut self) -> Duration { + self.measure(true) + } + + /// A failed, reversed, or cross-thread clock uses elapsed time for the rest of this window. + fn measure(&mut self, exact: bool) -> Duration { + #[cfg(target_os = "linux")] + if self.cpu.is_some() && Some(current().id()) != self.thread { + self.cpu = None; + } + if let Some(started) = self.cpu { + if !exact && self.sampled_at.elapsed() < self.sample_interval { + return self.last_elapsed; + } + if let Some(elapsed) = thread_cpu().and_then(|now| now.checked_sub(started)) + && elapsed >= self.last_elapsed + { + self.sampled_at = Instant::now(); + self.last_elapsed = elapsed; + return elapsed; + } + self.cpu = None; + } + self.last_elapsed = self.last_elapsed.max(self.wall.elapsed()); + self.last_elapsed + } +} + +/// Read an absolute counter without retaining a thread-bound handle in movable VM state. +/// CPU mode is Linux-only, where `nix` reads the counter without `unsafe`. +pub(super) fn thread_cpu() -> Option { + #[cfg(all(feature = "cpu-clock", target_os = "linux"))] + { + let time = ClockId::from_raw(CLOCK_THREAD_CPUTIME_ID).now().ok()?; + Some(Duration::new( + time.tv_sec().try_into().ok()?, + time.tv_nsec().try_into().ok()?, + )) + } + #[cfg(not(all(feature = "cpu-clock", target_os = "linux")))] + { + None + } +} + +#[cfg(test)] +#[path = "../../tests/unit/execution_clock.rs"] +mod tests; diff --git a/crates/bashkit-monty-types/src/results.rs b/crates/bashkit-monty-types/src/results.rs index b631cca34..afee86262 100644 --- a/crates/bashkit-monty-types/src/results.rs +++ b/crates/bashkit-monty-types/src/results.rs @@ -1,7 +1,7 @@ //! Host-supplied results fed back into a suspended run: //! [`NameLookupResult`] and [`ExtFunctionResult`]. -use crate::{exceptions::MontyException, object::MontyObject}; +use crate::{exceptions::MontyException, import::ModuleFile, object::MontyObject}; /// Result of a name lookup from the host. /// /// When the VM encounters an unresolved name (or a lazy attribute on a @@ -57,6 +57,9 @@ pub enum ExtFunctionResult { Future(u32), /// Raises `NameError`, or `ModuleNotFoundError` for an `import` call. NotFound(String), + /// Answers an `import` call with the module's `.py` file, which the sandbox + /// runs as the module. Only valid for an import with a non-empty search path. + ModuleFile(ModuleFile), } impl From for ExtFunctionResult { diff --git a/crates/bashkit-monty-types/src/type_checking.rs b/crates/bashkit-monty-types/src/type_checking.rs index 0582d58ad..cc3b9479a 100644 --- a/crates/bashkit-monty-types/src/type_checking.rs +++ b/crates/bashkit-monty-types/src/type_checking.rs @@ -192,6 +192,7 @@ impl Error for ModuleStubError {} /// Imports of these modules never reach the host, so host modules cannot use these names. /// Keep in sync with the runtime's `StandardLib`. pub const SANDBOX_MODULE_NAMES: &[&str] = &[ + "annotationlib", "asyncio", "base64", "binascii", @@ -202,6 +203,7 @@ pub const SANDBOX_MODULE_NAMES: &[&str] = &[ "dataclasses", "datetime", "decimal", + "fnmatch", "functools", "gc", "hashlib", @@ -227,11 +229,13 @@ pub const CHECKER_MODULE_NAMES: &[&str] = &[ "__future__", "__main__", "_collections_abc", + "_io", "_typeshed", "abc", "builtins", "enum", "genericpath", + "io", "ty_extensions", "types", "typing_extensions", diff --git a/crates/bashkit-monty-types/tests/unit/execution_clock.rs b/crates/bashkit-monty-types/tests/unit/execution_clock.rs new file mode 100755 index 000000000..52df6d227 --- /dev/null +++ b/crates/bashkit-monty-types/tests/unit/execution_clock.rs @@ -0,0 +1,64 @@ +use std::{thread, time::Duration}; + +use super::{ExecutionClock, ExecutionInstant}; + +#[cfg(target_os = "linux")] +#[test] +fn cached_sample_preserves_the_last_reported_duration() { + let mut window = ExecutionInstant::now(ExecutionClock::Cpu, None); + window.cpu = Some(Duration::ZERO); + window.thread = Some(thread::current().id()); + window.sample_interval = Duration::from_mins(1); + window.last_elapsed = Duration::from_nanos(42); + assert_eq!(window.elapsed(), Duration::from_nanos(42)); +} + +#[test] +fn unavailable_counter_keeps_the_monotonic_elapsed_floor() { + let mut window = ExecutionInstant::now(ExecutionClock::Cpu, None); + window.cpu = None; + window.last_elapsed = Duration::from_mins(1); + assert_eq!(window.elapsed(), Duration::from_mins(1)); + assert_eq!(window.elapsed_at_stop(), Duration::from_mins(1)); + assert!(window.cpu.is_none()); +} + +#[test] +fn reversed_counter_latches_elapsed_fallback() { + let mut window = ExecutionInstant::now(ExecutionClock::Cpu, None); + window.cpu = Some(Duration::MAX); + window.elapsed_at_stop(); + assert!(window.cpu.is_none()); + let before = window.last_elapsed; + assert!(window.elapsed_at_stop() >= before); + assert!(window.cpu.is_none()); +} + +#[test] +fn regressed_sample_cannot_refund_consumed_time() { + let mut window = ExecutionInstant::now(ExecutionClock::Cpu, None); + window.cpu = Some(Duration::ZERO); + window.last_elapsed = Duration::MAX; + assert_eq!(window.elapsed_at_stop(), Duration::MAX); + assert!(window.cpu.is_none()); +} + +#[test] +fn wall_mode_never_arms_the_cpu_counter() { + let mut window = ExecutionInstant::now(ExecutionClock::Wall, None); + assert!(window.cpu.is_none()); + thread::sleep(Duration::from_millis(10)); + assert!(window.elapsed_at_stop() >= Duration::from_millis(10)); + assert!(window.cpu.is_none()); +} + +#[test] +fn wall_clock_is_always_available() { + assert!(ExecutionClock::Wall.is_available()); +} + +#[cfg(not(all(feature = "cpu-clock", target_os = "linux")))] +#[test] +fn cpu_clock_is_unavailable_without_the_feature_or_off_linux() { + assert!(!ExecutionClock::Cpu.is_available()); +} diff --git a/crates/bashkit-monty/Cargo.toml b/crates/bashkit-monty/Cargo.toml index 4b83ed39c..29931eaa9 100644 --- a/crates/bashkit-monty/Cargo.toml +++ b/crates/bashkit-monty/Cargo.toml @@ -1,11 +1,11 @@ -# Fork of pydantic/monty monty-1.4.0 (MIT) for bashkit's in-process Python. +# Fork of pydantic/monty monty-1.5.0 (MIT) for bashkit's in-process Python. # # Important decision (security): bashkit runs many tenants' Python in one # process. Upstream Monty enforces `max_memory` through a process-wide # allocator counter and has no in-VM host checkpoint, so bashkit carries a # small patch in `bashkit-monty-types` (`set_memory_probe`, pydantic/monty#740, # and `set_checkpoint_hook`) and republishes `monty` against it. Source is -# upstream monty-1.4.0 unchanged except marked edits; the library names stay `monty` / +# upstream monty-1.5.0 unchanged except marked edits; the library names stay `monty` / # `monty_types` so code reads as upstream. Drop both crates once upstream ships # the hooks. See knowledge/runtimes/python-builtin.md. # @@ -22,7 +22,7 @@ rust-version = "1.96" authors = ["Samuel Colvin ", "Everruns"] license = "MIT" repository.workspace = true -description = "Fork of pydantic/monty 1.4.0 (secure, snapshotable Python sandbox) built against bashkit-monty-types, for bashkit's python3" +description = "Fork of pydantic/monty 1.5.0 (secure, snapshotable Python sandbox) built against bashkit-monty-types, for bashkit's python3" keywords = ["python", "interpreter", "sandbox", "bashkit"] categories = ["compilers", "emulators"] readme = "README.md" @@ -36,13 +36,9 @@ test = false doctest = false [dependencies] -monty-types = { package = "bashkit-monty-types", path = "../bashkit-monty-types", version = "0.20.3" } +monty-types = { package = "bashkit-monty-types", path = "../bashkit-monty-types", version = "0.20.3", features = ["cpu-clock"] } ahash = { version = "0.8.0", features = ["serde"] } chrono = { version = "0.4", features = ["serde"] } -# bashkit fork: declared by bashkit's own crates too (workspace: 0.20), so -# upstream's 0.17 here put two majors of fancy-regex in the graph. Also what -# Dependabot keeps proposing: it does not ignore shared deps, and the proposal -# edits this manifest. Drop the marker when upstream Monty reaches 0.20. fancy-regex = { version = "0.20.0" } # bashkit fork: same, aligned with the workspace's 0.4. This does not drop # 0.3 from the graph (ahash, fastbloom and rand_core still pull it); it stops @@ -63,7 +59,7 @@ jiter = { version = "0.18.0", features = ["num-bigint"] } libm = { version = "0.2" } memchr = { version = "2.7" } minicbor-serde = { version = "0.7", features = ["alloc"], default-features = false } -monty-macros = { version = "1.4.0" } +monty-macros = { version = "=1.5.0" } num-bigint = { version = "0.4", features = ["serde"] } num-integer = { version = "0.1" } num-traits = { version = "0.2" } @@ -85,6 +81,12 @@ unicode-general-category = { version = "1" } unicode-normalization = { version = "0.1" } unicode_names2 = { version = "1" } +# Upstream's `#[cfg(test)]` modules inside src/ need this; the drift check +# deliberately skips dev-dependencies, and CI's `--workspace --lib` builds the +# lib test target even though `[lib] test = false` excludes it by default. +[dev-dependencies] +serde_json = { version = "1.0" } + [features] memory-model-checks = [] ref-count-return = ["test-hooks"] diff --git a/crates/bashkit-monty/README.md b/crates/bashkit-monty/README.md index 7c4069a55..ce1542401 100644 --- a/crates/bashkit-monty/README.md +++ b/crates/bashkit-monty/README.md @@ -122,11 +122,20 @@ Successful decoding is not evidence of authenticity or validity. Async host functions are supported too: `FunctionCall::resume_pending` continues execution with a pending future the sandboxed code can `await`; when all tasks are blocked, execution yields `RunProgress::ResolveFutures` for the host to supply results. When `FunctionCall::allow_eager_await` is true the call is awaited immediately and no other task can run, so a host that already has the result can pass it to `FunctionCall::resume_eager` and skip the `ResolveFutures` round trip. `OsCall::allow_eager_await` says the same of an `asyncio.sleep` the host has already waited out. -Imports of unknown modules suspend with `OsFunctionCall::Import` and the top-level module name. -The host's answer becomes the module; dotted imports read subsequent components as attributes of that value. +Imports of unknown modules suspend with `OsFunctionCall::Import`, whose `ImportArgs` carry the dotted module name and +its search path: the working directory for a top-level name, or a file package's `__path__` for its submodules. +A returned value becomes the module; dotted imports read subsequent components as attributes of that value. Hosts usually return a host-backed class instance containing the module's attributes. -`ExtFunctionResult::NotFound`, or running without a host, raises `ModuleNotFoundError`. +A host with no such module can answer `ExtFunctionResult::ModuleFile` with the module's `.py` file instead: +`ImportArgs::candidates` lists `/name/__init__.py`, then `/name.py`, for each search directory, +`find_module_file` reads them in turn with a function the host supplies (a missing file moves on, any other read error +is the answer), and `MountTable::read_module` reads one through the mounts. +The sandbox runs the file as the module and caches it for the session. +`ExtFunctionResult::NotFound` (what `OsFunctionCall::no_handler_result` answers), or running without a host, raises +`ModuleNotFoundError`; an exception the host raises for the import is raised as it is. The worker requests module type stubs through `OsFunctionCall::ImportStubs`; the interpreter never raises it. +`typing.get_type_hints()` of a host function or class suspends with `OsFunctionCall::GetTypeHints`; the host's dict +answer is the call's result, and running without a host gives `{}`. ## Other pieces @@ -149,6 +158,8 @@ The worker requests module type stubs through `OsFunctionCall::ImportStubs`; the Defaults use the system clock, UTC and OS entropy, with sleeps capped at ten seconds. System sleeps suspend for the host to wait without its `os` handler; standard execution waits inline. `CallHost` delegates to the host through `RunProgress::OsCall`. + A loaded dump keeps the policy it was taken under until the host calls `MontyRepl::set_os_policy` or + `ReplProgress::set_os_policy`; the worker applies the restoring checkout's policy this way. ## Monty crates diff --git a/crates/bashkit-monty/src/annotations.rs b/crates/bashkit-monty/src/annotations.rs new file mode 100644 index 000000000..d2be27f79 --- /dev/null +++ b/crates/bashkit-monty/src/annotations.rs @@ -0,0 +1,311 @@ +//! Runtime side of PEP 649 annotations. +//! +//! The compiler turns a `def`'s or class body's annotations into an +//! `__annotate__(format)` function (see `Parser::synthesize_annotate`). This +//! module exposes it: `f.__annotate__` / `f.__annotations__`, a class's lazily +//! computed and cached `__annotations__`, and the private helpers frozen code +//! uses to call an annotate function in each `annotationlib.Format`. + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::{CallResult, MissingNames, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + frozen::{FrozenFunction, FrozenFunctions}, + heap::{DropGuard, DropWithContext, HeapData, HeapId, HeapReadOutput}, + heap_data::FunctionDefaults, + intern::{FunctionId, StaticStrings}, + modules::ModuleFunctions, + types::{Dict, dict}, + value::Value, +}; + +/// `annotationlib.Format.VALUE`, the format `__annotations__` evaluates in. +const VALUE_FORMAT: i64 = 1; + +/// `__monty_class_annotations(cls, annotate, classdict, call_annotate, cache)`: +/// evaluates a class's `__annotate__` in `VALUE` format under its namespace and +/// caches the dict, so a later access returns the same object as in CPython. +pub(crate) const CLASS_ANNOTATIONS_SOURCE: &str = r" +def __monty_class_annotations(cls, annotate, classdict, call_annotate, cache): + result = call_annotate(annotate, classdict, 1, 0, cls, True) + cache(cls, result) + return result +"; + +/// `f.__annotate__` and `f.__annotations__` of a `def`, the only attributes +/// Monty's functions have (see `limitations/language.md`); `None` for any other +/// name. `globals` is the exec dict the `def` was made under, if any. +pub(crate) fn function_getattr( + func_id: FunctionId, + globals: Option, + attr: &str, + vm: &mut VM<'_>, +) -> Option> { + match attr { + "__annotate__" => Some(Ok(CallResult::Value(function_annotate(func_id, globals, vm)))), + "__annotations__" => Some(function_annotations(func_id, globals, vm)), + _ => None, + } +} + +/// `f.__annotate__(format)` and `f.__annotations__(...)`: the attribute, called. +/// `None` for any other name, which has no attribute to call. +pub(crate) fn function_call_attr( + func_id: FunctionId, + globals: Option, + attr: &str, + args: ArgValues, + vm: &mut VM<'_>, +) -> Option> { + // The guard releases `args` when there is no attribute or computing it fails. + let mut args_guard = DropGuard::new(args, vm); + let (_, vm) = args_guard.as_parts_mut(); + let callee = match function_getattr(func_id, globals, attr, vm) { + Some(Ok(callee)) => callee.require_synchronous(vm), + Some(Err(err)) => Err(err), + None => return None, + }; + let callee = match callee { + Ok(callee) => callee, + Err(err) => return Some(Err(err)), + }; + let (args, vm) = args_guard.into_parts(); + defer_drop!(callee, vm); + Some(vm.call_function(callee, args)) +} + +/// `f.__annotations__`: runs `__annotate__(VALUE)` on every access, since a +/// Monty function has no `__dict__` to cache the result in (see `limitations/typing.md`). +fn function_annotations(func_id: FunctionId, globals: Option, vm: &mut VM<'_>) -> RunResult { + let annotate = function_annotate(func_id, globals, vm); + defer_drop!(annotate, vm); + if matches!(annotate, Value::None) { + Ok(CallResult::Value(empty_dict(vm))) + } else { + vm.call_annotate(annotate, VALUE_FORMAT, None, MissingNames::Raise) + } +} + +/// The function value of a `def`'s `__annotate__`, sharing the `def`'s exec +/// globals so it resolves names where the `def` does; `None` when unannotated. +pub(crate) fn function_annotate(func_id: FunctionId, globals: Option, vm: &mut VM<'_>) -> Value { + let Some(annotate_id) = vm.interns.get_function(func_id).annotate else { + return Value::None; + }; + match globals { + None => Value::DefFunction(annotate_id), + Some(dict) => { + vm.heap.inc_ref(dict); + let function = FunctionDefaults { + func_id: annotate_id, + defaults: Vec::new(), + globals: Some(dict), + }; + Value::Ref(vm.heap.allocate(HeapData::FunctionDefaults(function))) + } + } +} + +/// `C.__annotations__`: the dict the class body or a caller bound, else the +/// result of its `__annotate__`, evaluated on first access and cached under +/// `__annotations_cache__` as CPython does; `{}` for an unannotated class. +pub(crate) fn class_annotations(class_id: HeapId, vm: &mut VM<'_>) -> RunResult { + if let Some(stored) = stored_class_annotations(class_id, vm) { + return Ok(CallResult::Value(stored)); + } + if let Some(annotate) = class_annotate(class_id, vm) { + defer_drop!(annotate, vm); + let classdict = class_namespace_copy(class_id, vm)?; + defer_drop!(classdict, vm); + vm.heap.inc_ref(class_id); + vm.call_frozen_exact( + FrozenFunction::ClassAnnotations, + [ + Value::Ref(class_id), + annotate.clone_with_heap(vm), + classdict.clone_with_heap(vm), + Value::ModuleFunction(ModuleFunctions::Frozen(FrozenFunctions::CallAnnotate)), + Value::ModuleFunction(ModuleFunctions::Frozen(FrozenFunctions::CacheClassAnnotations)), + ], + ) + } else { + // The guard releases the dict if caching it fails. + let mut annotations_guard = DropGuard::new(empty_dict(vm), vm); + let (annotations, vm) = annotations_guard.as_parts_mut(); + set_class_attr( + class_id, + StaticStrings::DunderAnnotationsCache, + annotations.clone_with_heap(vm), + vm, + )?; + let (annotations, _) = annotations_guard.into_parts(); + Ok(CallResult::Value(annotations)) + } +} + +/// What a class's `__annotations__` or `__annotations_cache__` binds, owned: +/// the PEP 563 dict a class body stored, a dict a caller assigned, or a cached +/// evaluation. `None` when the annotations are still to be evaluated. +pub(crate) fn stored_class_annotations(class_id: HeapId, vm: &VM<'_>) -> Option { + [StaticStrings::DunderAnnotations, StaticStrings::DunderAnnotationsCache] + .into_iter() + .find_map(|name| class_member(class_id, name, vm)) +} + +/// A class's `__annotate__`, owned: stored as `__annotate_func__` by a compiled +/// class body and as `__annotate__` by a namespace handed to `type()`, the two +/// keys CPython's `get_annotate_from_class_namespace` reads. +pub(crate) fn class_annotate(class_id: HeapId, vm: &VM<'_>) -> Option { + [StaticStrings::DunderAnnotateFunc, StaticStrings::DunderAnnotate] + .into_iter() + .find_map(|name| class_member(class_id, name, vm)) + .filter(|annotate| !matches!(annotate, Value::None)) +} + +/// `C.__annotations__ = value`: replaces a dict the namespace binds as +/// `__annotations__`, else is stored as the cached dict; either way the class's +/// `__annotate__` is set aside, as CPython's `type.__annotations__` setter does. +pub(crate) fn set_class_annotations(class_id: HeapId, value: Value, vm: &mut VM<'_>) -> RunResult<()> { + let key = if has_class_member(class_id, StaticStrings::DunderAnnotations, vm) { + StaticStrings::DunderAnnotations + } else { + StaticStrings::DunderAnnotationsCache + }; + set_class_attr(class_id, key, value, vm)?; + set_class_attr(class_id, StaticStrings::DunderAnnotateFunc, Value::None, vm) +} + +/// A fresh heap dict holding the class namespace's entries, CPython's +/// `dict(vars(cls))`: the locals a class's annotations evaluate against. +/// The pair buffer and the dict are preflighted like a dict copy. +pub(crate) fn class_namespace_copy(class_id: HeapId, vm: &mut VM<'_>) -> RunResult { + let HeapData::Class(class) = vm.heap.get(class_id) else { + unreachable!("class_namespace_copy takes a class"); + }; + dict::check_pairs_into_fresh_dict(class.namespace().len(), vm)?; + let pairs = class + .namespace() + .iter() + .map(|(name, value)| (name.clone_with_heap(vm.heap), value.clone_with_heap(vm.heap))) + .collect(); + let dict = Dict::from_pairs(pairs, vm)?; + Ok(Value::Ref(vm.heap.allocate(HeapData::Dict(dict)))) +} + +/// Frozen helper: calls `annotate(format)` under `classdict` for `owner`, with +/// unresolved names handled per `fake` (see [`missing_names`]). +pub(crate) fn call_annotate_helper(args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let CallAnnotateArgs { + annotate, + classdict, + format, + fake, + owner, + is_class, + } = CallAnnotateArgs::from_args(args, vm)?; + defer_drop!(annotate, vm); + defer_drop!(classdict, vm); + defer_drop!(owner, vm); + let Value::Int(format) = format else { + unreachable!("frozen code passes the format as an int") + }; + let missing = missing_names(&fake, owner, matches!(is_class, Value::Bool(true)), vm); + vm.call_annotate(annotate, format, classdict.ref_id(), missing) +} + +/// What an unresolved name loads as while an `__annotate__` function runs, from +/// the fake-globals mode frozen code passes: `0` a `NameError` (the function +/// runs as written), `1` a `ForwardRef` stringifier for unresolved names, `2` +/// one for every name — CPython's `_StringifierDict` for `FORWARDREF` and +/// `STRING` — and `3` a `NameError` without asking the host. +/// `owner` is borrowed, cloned only when a stringifier needs it. +fn missing_names(fake: &Value, owner: &Value, is_class: bool, vm: &VM<'_>) -> MissingNames { + match fake { + Value::Int(0) => MissingNames::Raise, + Value::Int(every_name @ (1 | 2)) => MissingNames::ForwardRef { + owner: owner.clone_with_heap(vm.heap), + is_class, + every_name: *every_name == 2, + }, + Value::Int(3) => MissingNames::NameError, + _ => unreachable!("frozen code passes the fake-globals mode as an int"), + } +} + +/// Arguments of the private `call_annotate` helper. +#[derive(FromArgs)] +#[from_args(name = "call_annotate")] +struct CallAnnotateArgs { + #[from_args(pos_only)] + annotate: Value, + #[from_args(pos_only)] + classdict: Value, + #[from_args(pos_only)] + format: Value, + #[from_args(pos_only)] + fake: Value, + #[from_args(pos_only)] + owner: Value, + #[from_args(pos_only)] + is_class: Value, +} + +/// Frozen helper: caches a class's evaluated annotations under +/// `__annotations_cache__`, rejecting a non-dict as CPython's `type.__annotations__` does. +pub(crate) fn cache_class_annotations_helper(args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let (cls, annotations) = args.get_two_args("cache", vm.heap)?; + defer_drop!(cls, vm); + defer_drop!(annotations, vm); + let Value::Ref(class_id) = cls else { + unreachable!("frozen code passes the class") + }; + if !matches!(annotations, Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::Dict(_))) { + let type_name = annotations.py_type_name(vm); + return Err(ExcType::type_error(format!( + "__annotate__ returned non-dict of type '{type_name}'" + ))); + } + set_class_attr( + *class_id, + StaticStrings::DunderAnnotationsCache, + annotations.clone_with_heap(vm), + vm, + )?; + Ok(Value::None) +} + +/// An owned clone of the class namespace member `name`, if bound. +fn class_member(class_id: HeapId, name: StaticStrings, vm: &VM<'_>) -> Option { + let HeapData::Class(class) = vm.heap.get(class_id) else { + unreachable!("class_member takes a class"); + }; + class + .namespace() + .get_by_str(name.into(), vm.heap, vm.interns) + .map(|value| value.clone_with_heap(vm.heap)) +} + +/// Whether the class namespace binds `name`. +fn has_class_member(class_id: HeapId, name: StaticStrings, vm: &VM<'_>) -> bool { + let HeapData::Class(class) = vm.heap.get(class_id) else { + unreachable!("has_class_member takes a class"); + }; + class.namespace().get_by_str(name.into(), vm.heap, vm.interns).is_some() +} + +/// Binds `name` to `value` in the class namespace, taking ownership of `value`. +fn set_class_attr(class_id: HeapId, name: StaticStrings, value: Value, vm: &mut VM<'_>) -> RunResult<()> { + let HeapReadOutput::Class(class) = vm.heap.read(class_id) else { + unreachable!("set_class_attr takes a class"); + }; + let name = Value::InternString(vm.interns.intern_static(name)); + let replaced = class.set_attr(name, value, vm)?; + replaced.drop_with(vm); + Ok(()) +} + +/// A fresh, empty heap dict. +pub(crate) fn empty_dict(vm: &VM<'_>) -> Value { + Value::Ref(vm.heap.allocate(HeapData::Dict(Dict::new()))) +} diff --git a/crates/bashkit-monty/src/args/bind_native.rs b/crates/bashkit-monty/src/args/bind_native.rs index 6857a66c5..551834e3b 100644 --- a/crates/bashkit-monty/src/args/bind_native.rs +++ b/crates/bashkit-monty/src/args/bind_native.rs @@ -217,9 +217,10 @@ fn bind_slow( // conversion, and conflict error); stash the first for `finish`. value.drop_with(vm); if bound.deferred.as_ref().is_none_or(|d| d.unknown.is_none()) { + let name = key_str.into_string(vm.interns); let err = match spec.family { - ErrorFamily::C { .. } => ExcType::type_error_c_unexpected_keyword(key_str.as_str(vm.interns)), - _ => ExcType::type_error_unexpected_keyword(spec.func_name, key_str.as_str(vm.interns)), + ErrorFamily::C { .. } => ExcType::type_error_c_unexpected_keyword(&name), + _ => ExcType::type_error_unexpected_keyword(spec.func_name, &name), }; bound.deferred_mut().unknown = Some(err); } @@ -227,7 +228,7 @@ fn bind_slow( } None => { value.drop_with(vm); - let name = key_str.as_str(vm.interns).to_owned(); + let name = key_str.into_string(vm.interns); key.drop_with(vm); let err_name = spec.kwarg_error_name.unwrap_or(spec.func_name); return Err(ExcType::type_error_unexpected_keyword(err_name, &name)); diff --git a/crates/bashkit-monty/src/args/from_value.rs b/crates/bashkit-monty/src/args/from_value.rs index e0359df34..c12135513 100644 --- a/crates/bashkit-monty/src/args/from_value.rs +++ b/crates/bashkit-monty/src/args/from_value.rs @@ -369,7 +369,7 @@ impl StrArg { /// Borrows the text. Infallible: the constructor validated str-ness and a /// live value's type cannot change. pub fn as_str<'a>(&'a self, vm: &'a VM<'_>) -> &'a str { - match self.0.to_str(vm) { + match self.0.try_to_str(vm) { Ok(s) => s, Err(_) => unreachable!("StrArg always holds a str"), } diff --git a/crates/bashkit-monty/src/args/mod.rs b/crates/bashkit-monty/src/args/mod.rs index 40f2cd68c..a1fa27d02 100644 --- a/crates/bashkit-monty/src/args/mod.rs +++ b/crates/bashkit-monty/src/args/mod.rs @@ -22,7 +22,7 @@ use crate::{ object_bridge::{CallArgsExt, GraphExporter}, parse::ParseError, types::{Dict, dict::DictIntoIter}, - value::Value, + value::{EitherStr, Value}, }; /// Type for method call arguments. @@ -227,8 +227,10 @@ impl ArgValues { } /// Exports the arguments into one arena for delivery to an external - /// function, so an object passed twice crosses once. - pub fn into_call_args(self, vm: &mut VM<'_>) -> CallArgs { + /// function, so an object passed twice crosses once. Fails only with a + /// resource limit hit during export, where a user `__repr__` can run; + /// callers outside the run loop wrap it in [`VM::export_on_clock`]. + pub fn into_call_args(self, vm: &mut VM<'_>) -> RunResult { let mut exporter = GraphExporter::new(); let mut call = CallArgs::new(); match self { @@ -246,8 +248,8 @@ impl ArgValues { kwargs.export_into(&mut call, &mut exporter, vm); } } - *unstable::call_args_parts_mut(&mut call).0 = exporter.finish(vm); - call + *unstable::call_args_parts_mut(&mut call).0 = exporter.finish(vm)?; + Ok(call) } /// The first positional argument, if any, without consuming the arguments. @@ -430,7 +432,9 @@ impl KwargsValues { pub fn first_key(&self, heap: &Heap, interns: &Interns) -> RunResult> { let key = match self { Self::Empty => return Ok(None), - Self::Inline(kvs) => return Ok(kvs.first().map(|(id, _)| interns.get_str(*id).to_owned())), + Self::Inline(kvs) => { + return Ok(kvs.first().map(|(id, _)| EitherStr::Interned(*id).into_string(interns))); + } Self::Pairs(kvs) => kvs.first().map(|(key, _)| key), Self::Dict(dict) => dict.iter().next().map(|(key, _)| key), }; @@ -438,7 +442,7 @@ impl KwargsValues { None => Ok(None), Some(key) => key .as_either_str(heap) - .map(|key| Some(key.as_str(interns).to_owned())) + .map(|key| Some(key.into_string(interns))) .ok_or_else(ExcType::type_error_kwargs_nonstring_key), } } diff --git a/crates/bashkit-monty/src/builtins/chr.rs b/crates/bashkit-monty/src/builtins/chr.rs index 3c59d0e25..babe5ff4a 100644 --- a/crates/bashkit-monty/src/builtins/chr.rs +++ b/crates/bashkit-monty/src/builtins/chr.rs @@ -15,7 +15,7 @@ pub fn builtin_chr(vm: &mut VM<'_>, args: ArgValues) -> RunResult { defer_drop!(value, vm); let index = value.saturating_index(vm)?; if let Some(c) = u32::try_from(index).ok().and_then(char::from_u32) { - Ok(allocate_char(c, vm.heap)) + Ok(allocate_char(c)) } else { Err(ExcType::value_error("chr() arg not in range(0x110000)")) } diff --git a/crates/bashkit-monty/src/builtins/eval_exec.rs b/crates/bashkit-monty/src/builtins/eval_exec.rs index 0d19a0df6..6f46472fc 100644 --- a/crates/bashkit-monty/src/builtins/eval_exec.rs +++ b/crates/bashkit-monty/src/builtins/eval_exec.rs @@ -6,9 +6,11 @@ use std::{str, sync::Arc}; +use ruff_text_size::TextSize; + use crate::{ args::{ArgValues, FromArgs, Signature}, - bytecode::{CallResult, Compiler, FrameNamespace, VM}, + bytecode::{CallResult, Compiler, FrameGlobals, FrameNamespace, MissingNames, VM}, defer_drop, exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, expressions::{Identifier, Node}, @@ -16,7 +18,10 @@ use crate::{ heap::{DropGuard, HeapData, HeapId}, intern::{CompileInterns, FunctionId, StaticStrings}, name_map::NameMap, - parse::{CodeRange, parse_expression_with_interner, parse_module_with_filename_id}, + parse::{ + CodeRange, ParseError, ParsedModule, parse_expression_with_interner, parse_module_with_filename_id, + reject_leading_bom, + }, prepare::{SnippetNames, prepare_snippet}, types::{Type, py_trait::PyTrait}, value::Value, @@ -112,49 +117,210 @@ fn run_snippet( locals: Option, vm: &mut VM<'_>, ) -> RunResult { - if source.contains('\0') { - return Err( - SimpleException::new_msg(ExcType::SyntaxError, "source code string cannot contain null bytes").into(), - ); - } + reject_null_bytes(source)?; for dict in globals.into_iter().chain(locals) { vm.heap.inc_ref(dict); } let (names, namespace) = vm.snippet_namespace(globals, locals)?; - let globals_len = vm.global_names.len(); - let result = compile_and_push(builtin, source, names, namespace, vm); - if result.is_err() { - vm.global_names.truncate(globals_len); + let kind = match builtin { + Builtin::Eval => SnippetSource::Eval, + Builtin::Exec => SnippetSource::Exec, + }; + compile_and_push(kind, source, names, namespace, vm)?; + Ok(CallResult::FramePushed) +} + +/// Evaluates one annotation string for `typing.get_type_hints()`, `ForwardRef.evaluate()` +/// and `get_annotations(eval_str=True)`. +/// +/// Runs in borrowed `globals` / `locals` dicts (`None` globals means the module slots), +/// with `globals_first` letting bound slot globals shadow `locals`, and `missing` +/// choosing between `NameError` and a `ForwardRef` stringifier for an unresolved +/// name. A `forward_ref` compiles as CPython's `ForwardRef` does: a compile error or +/// leading indentation raises its "must be an expression" error. +/// +/// Each distinct text and mode compiles once per session, so names are always +/// resolved at run time: a snippet compiled when `int` was the builtin must see a +/// later `int = str`. The namespace is built here, not by `snippet_namespace`, +/// which would inherit the calling frame's: the caller is frozen code. +pub(crate) fn eval_hint( + source: &Value, + globals: Option, + locals: Option, + globals_first: bool, + forward_ref: bool, + missing: MissingNames, + vm: &mut VM<'_>, +) -> RunResult { + let mut missing_guard = DropGuard::new(missing, vm); + let (_, vm) = missing_guard.as_parts_mut(); + let text = snippet_source("eval", source, vm)?; + if forward_ref && first_code_line_indented(&text) { + return Err(ExcType::forward_ref_not_expression(&text)); } - result + let not_expression = |err: RunError| { + if forward_ref && err.is_catchable(ExcType::SyntaxError) { + ExcType::forward_ref_not_expression(&text) + } else { + err + } + }; + reject_null_bytes(&text).map_err(not_expression)?; + // The namespace owns `missing` from here, on every path. + let (missing, vm) = missing_guard.into_parts(); + for dict in globals.into_iter().chain(locals) { + vm.heap.inc_ref(dict); + } + let (globals, names) = match globals { + Some(dict) => (FrameGlobals::Dict(dict), SnippetNames::NameOverDict), + None => (FrameGlobals::Slots, SnippetNames::NameOverSlots), + }; + let namespace = Box::new(FrameNamespace::Snippet { + globals, + locals, + globals_first, + missing, + }); + if let Some(func_id) = vm.interns.hint_snippet(names, &text) { + vm.push_snippet_frame(func_id, None, namespace)?; + } else { + let func_id = compile_and_push(SnippetSource::Eval, &text, names, namespace, vm).map_err(not_expression)?; + vm.interns.set_hint_snippet(names, text, func_id); + } + Ok(CallResult::FramePushed) +} + +/// What runtime-compiled source is: it decides how the source parses, the +/// filename its frames show and how its compile errors read. +#[derive(Clone, Copy)] +pub(crate) enum SnippetSource<'a> { + /// An `eval()` expression, shown as ``. + Eval, + /// An `exec()` module body, shown as ``. + Exec, + /// An imported `.py` file's module body, shown as its virtual `path`. + File { path: &'a str }, } /// Compiles privately and publishes only after the snippet's frame is admitted. -fn compile_and_push( - builtin: Builtin, +/// +/// Provisional global slots are released if compilation or admission fails. +pub(crate) fn compile_and_push( + kind: SnippetSource<'_>, source: &Arc, names: SnippetNames, namespace: Box, vm: &mut VM<'_>, -) -> RunResult { +) -> RunResult { + let globals_len = vm.global_names.len(); let mut namespace_guard = DropGuard::new(namespace, vm); let (_, vm) = namespace_guard.as_parts_mut(); + match compile_snippet(kind, source, names, vm) { + Ok((func_id, overlay)) => { + // `push_snippet_frame` owns the namespace from here, on every path. + let (namespace, vm) = namespace_guard.into_parts(); + let pushed = vm.push_snippet_frame(func_id, Some(overlay), namespace); + if pushed.is_ok() { + vm.globals.resize_with(vm.global_names.len(), || Value::Undefined); + } else { + vm.global_names.truncate(globals_len); + } + pushed.map(|()| func_id) + } + // The guard releases the namespace's dict references. + Err(err) => { + let (_, vm) = namespace_guard.as_parts_mut(); + vm.global_names.truncate(globals_len); + Err(err) + } + } +} + +/// The `SyntaxError` for snippet source holding a NUL, checked before any namespace is built. +fn reject_null_bytes(source: &str) -> RunResult<()> { + if source.contains('\0') { + Err(SimpleException::new_msg(ExcType::SyntaxError, "source code string cannot contain null bytes").into()) + } else { + Ok(()) + } +} + +/// Whether the first line of code in `source` is indented, which `compile()` rejects +/// but `eval()` strips. Like CPython's tokenizer, it skips blank and comment-only +/// lines, and a form feed resets the column. +fn first_code_line_indented(source: &str) -> bool { + source + .lines() + .find_map(|line| { + let mut indented = false; + for c in line.chars() { + match c { + ' ' | '\t' => indented = true, + '\x0c' => indented = false, + '#' => return None, + _ => return Some(indented), + } + } + None + }) + .unwrap_or(false) +} + +/// Parses, prepares and compiles `source` into an unpublished overlay, returning +/// the snippet function's ID within it. +fn compile_snippet<'h>( + kind: SnippetSource<'_>, + source: &Arc, + names: SnippetNames, + vm: &mut VM<'h>, +) -> RunResult<(FunctionId, CompileInterns<'h>)> { let mut overlay = CompileInterns::new(vm.interns); - let filename_id = overlay.add_eval_source(Arc::clone(source)); + let filename_id = match kind { + SnippetSource::File { path } => overlay.add_file_source(Arc::from(path), Arc::clone(source)), + SnippetSource::Eval | SnippetSource::Exec => overlay.add_eval_source(Arc::clone(source)), + }; let options = vm.env.options; - let nodes = match builtin { - Builtin::Exec => { - parse_module_with_filename_id(source, filename_id, &mut overlay, options.source_scan_threshold) - } - Builtin::Eval => { - let trimmed = source.trim_start(); - let skipped = u32::try_from(source.len() - trimmed.len()).unwrap_or(u32::MAX); - parse_expression_with_interner(trimmed, filename_id, &mut overlay, options.source_scan_threshold) - .map(|expr| vec![Node::Return(Some(expr))]) - .map_err(|e| e.shifted(skipped)) + let compile_error = |e: ParseError| match kind { + SnippetSource::File { path } => e.into_file_run_error(path, source), + SnippetSource::Eval | SnippetSource::Exec => e.into_run_error(source), + }; + // `eval()` / `exec()` inherit the caller's `from __future__ import annotations`, + // as CPython's do; an imported file starts afresh. + let inherited_future = match kind { + SnippetSource::Eval | SnippetSource::Exec => vm.frame_future_annotations(), + SnippetSource::File { .. } => false, + }; + let ParsedModule { + nodes, + future_annotations, + } = match kind { + // A file read from disk may open with a BOM; an `exec()` string may not. + SnippetSource::Exec => reject_leading_bom(source, TextSize::default(), filename_id).and_then(|()| { + parse_module_with_filename_id( + source, + filename_id, + &mut overlay, + options.source_scan_threshold, + inherited_future, + ) + }), + SnippetSource::File { .. } => parse_module_with_filename_id( + source, + filename_id, + &mut overlay, + options.source_scan_threshold, + inherited_future, + ), + SnippetSource::Eval => { + parse_expression_with_interner(source, filename_id, &mut overlay, options.source_scan_threshold).map( + |expr| ParsedModule { + nodes: vec![Node::Return(Some(expr))], + future_annotations: inherited_future, + }, + ) } } - .map_err(|e| e.into_run_error(source))?; + .map_err(compile_error)?; let globals_by_name = names == SnippetNames::NameOverDict; let mut scratch = NameMap::new(); @@ -163,9 +329,19 @@ fn compile_and_push( } else { &mut *vm.global_names }; - let nodes = prepare_snippet(nodes, &overlay, globals, names).map_err(|e| e.into_run_error(source))?; - let code = Compiler::compile_snippet(&nodes, &mut overlay, globals, options, globals_by_name) - .map_err(|e| e.into_run_error(source))?; + let nodes = prepare_snippet(nodes, &overlay, globals, names).map_err(compile_error)?; + let code = Compiler::compile_snippet( + &nodes, + &mut overlay, + globals, + options, + globals_by_name, + future_annotations, + ) + .map_err(|e| match kind { + SnippetSource::File { path } => e.into_file_run_error(path, source), + SnippetSource::Eval | SnippetSource::Exec => e.into_run_error(source), + })?; let position = CodeRange { filename: filename_id, @@ -193,19 +369,18 @@ fn compile_and_push( })?; overlay.push_function(function); - let (namespace, vm) = namespace_guard.into_parts(); - vm.push_snippet_frame(func_id, overlay, namespace)?; - vm.globals.resize_with(vm.global_names.len(), || Value::Undefined); - Ok(CallResult::FramePushed) + Ok((func_id, overlay)) } /// The snippet's text: a `str`, or `bytes` decoded as UTF-8. fn snippet_source(name: &str, source: &Value, vm: &mut VM<'_>) -> RunResult> { + if let Some(text) = source.as_str(vm) { + return Ok(Arc::from(text)); + } + let bytes: &[u8] = match source { - Value::InternString(id) => return Ok(Arc::from(vm.interns.get_str(*id))), Value::InternBytes(id) => vm.interns.get_bytes(*id), Value::Ref(id) => match vm.heap.get(*id) { - HeapData::Str(s) => return Ok(Arc::from(s.as_str())), HeapData::Bytes(b) => b.as_slice(), _ => return Err(source_type_error(name)), }, diff --git a/crates/bashkit-monty/src/builtins/getattr.rs b/crates/bashkit-monty/src/builtins/getattr.rs index 5b95e0b16..42f586e69 100644 --- a/crates/bashkit-monty/src/builtins/getattr.rs +++ b/crates/bashkit-monty/src/builtins/getattr.rs @@ -50,6 +50,19 @@ pub fn builtin_getattr(vm: &mut VM<'_>, args: ArgValues) -> RunResult Ok(CallResult::Value(value)), + // A frame computes the attribute (`__annotations__`). Without a default + // its result is the value; with one the frame runs here, so an + // `AttributeError` it raises selects the default as in CPython. + Ok(CallResult::FramePushed) => match default { + None => Ok(CallResult::FramePushed), + Some(d) => match CallResult::FramePushed.require_synchronous(vm) { + Ok(value) => Ok(CallResult::Value(value)), + Err(RunError::Exc(e)) if e.exc.exc_type() == ExcType::AttributeError => { + Ok(CallResult::Value(d.clone_with_heap(vm))) + } + Err(e) => Err(e), + }, + }, Ok(CallResult::AttrLookup { name, class_name, diff --git a/crates/bashkit-monty/src/builtins/hasattr.rs b/crates/bashkit-monty/src/builtins/hasattr.rs index d6c1096f1..36f6f122a 100644 --- a/crates/bashkit-monty/src/builtins/hasattr.rs +++ b/crates/bashkit-monty/src/builtins/hasattr.rs @@ -52,6 +52,16 @@ pub fn builtin_hasattr(vm: &mut VM<'_>, args: ArgValues) -> RunResult match CallResult::FramePushed.require_synchronous(vm) { + Ok(value) => { + value.drop_with(vm); + true + } + Err(RunError::Exc(e)) if e.exc.exc_type() == ExcType::AttributeError => false, + Err(e) => return Err(e), + }, Ok(CallResult::AttrLookup { name, class_name, diff --git a/crates/bashkit-monty/src/builtins/isinstance.rs b/crates/bashkit-monty/src/builtins/isinstance.rs index eaf29e368..aca811b44 100644 --- a/crates/bashkit-monty/src/builtins/isinstance.rs +++ b/crates/bashkit-monty/src/builtins/isinstance.rs @@ -34,7 +34,7 @@ pub fn builtin_isinstance(vm: &mut VM<'_>, args: ArgValues) -> RunResult /// - Tuples (possibly nested) of the above pub(crate) fn isinstance_check(obj: &Value, classinfo: &Value, vm: &mut VM<'_>) -> RunResult { match classinfo { - Value::Builtin(Builtins::Type(t)) => Ok(obj.py_type(vm).is_instance_of(*t)), + Value::Builtin(Builtins::Type(t)) => Ok(obj.py_type(vm).is_instance_of((*t).into())), Value::Builtin(Builtins::ExcType(handler_type)) => { Ok(matches!(obj.py_type(vm), Type::Exception(exc_type) if exc_type.is_subclass_of(*handler_type))) } @@ -93,7 +93,7 @@ fn isinstance_check_tuple<'h>(obj: &Value, tuple: &HeapRead<'h, Tuple>, vm: &mut for i in 0..len { match &tuple.get(vm.heap).as_slice()[i] { Value::Builtin(Builtins::Type(t)) => { - if obj.py_type(vm).is_instance_of(*t) { + if obj.py_type(vm).is_instance_of((*t).into()) { return Ok(true); } } diff --git a/crates/bashkit-monty/src/builtins/len.rs b/crates/bashkit-monty/src/builtins/len.rs index 5d15f859b..4fe66a6b8 100644 --- a/crates/bashkit-monty/src/builtins/len.rs +++ b/crates/bashkit-monty/src/builtins/len.rs @@ -4,7 +4,7 @@ use crate::{ args::ArgValues, bytecode::VM, defer_drop, - exception_private::{ExcType, ExcTypeExt, RunResult, SimpleException}, + exception_private::{ExcType, ExcTypeExt, RunResult}, types::PyTrait, value::Value, }; @@ -21,6 +21,6 @@ pub fn builtin_len(vm: &mut VM<'_>, args: ArgValues) -> RunResult { )) } else { let type_name = value.py_type_name(vm); - Err(SimpleException::new_msg(ExcType::TypeError, format!("object of type '{type_name}' has no len()")).into()) + Err(ExcType::type_error_no_len(&type_name)) } } diff --git a/crates/bashkit-monty/src/builtins/mod.rs b/crates/bashkit-monty/src/builtins/mod.rs index 45f582234..92f1bef01 100644 --- a/crates/bashkit-monty/src/builtins/mod.rs +++ b/crates/bashkit-monty/src/builtins/mod.rs @@ -10,7 +10,7 @@ mod bin; mod chr; mod divmod; mod enumerate; -mod eval_exec; +pub(crate) mod eval_exec; mod filter; mod format; mod getattr; @@ -48,7 +48,7 @@ use crate::{ bytecode::{CallResult, VM}, exception_private::{ExcType, ExcTypeExt, RunResult}, modules::csv, - types::Type, + types::{BuiltinType, Type}, value::Value, }; @@ -63,7 +63,7 @@ pub(crate) enum Builtins { /// An exception type constructor like `ValueError`, `TypeError`, etc. ExcType(ExcType), /// A type constructor like `list`, `dict`, `int`, etc. - Type(Type), + Type(BuiltinType), } impl Builtins { @@ -87,8 +87,8 @@ impl Builtins { Self::Function(b) => b.call(vm, args), Self::ExcType(exc) => exc.call(vm, args).map(CallResult::Value), // `DictReader(f)` on an unread file yields the read that loads it. - Self::Type(Type::CsvDictReader) => csv::dict_reader_call(vm, args), - Self::Type(t) => t.call(vm, args), + Self::Type(BuiltinType::CsvDictReader) => csv::dict_reader_call(vm, args), + Self::Type(t) => Type::from(t).call(vm, args), } } @@ -122,7 +122,7 @@ impl FromStr for Builtins { } else if let Ok(exc) = ExcType::from_str(s) { Ok(Self::ExcType(exc)) } else if let Some(t) = Type::from_builtin_name(s) { - Ok(Self::Type(t)) + Ok(Self::Type(t.try_into().expect("builtin names have static types"))) } else { Err(()) } diff --git a/crates/bashkit-monty/src/builtins/object_setattr.rs b/crates/bashkit-monty/src/builtins/object_setattr.rs index 03ad23907..aabbcbcf5 100644 --- a/crates/bashkit-monty/src/builtins/object_setattr.rs +++ b/crates/bashkit-monty/src/builtins/object_setattr.rs @@ -8,7 +8,6 @@ use crate::{ defer_drop, exception_private::{ExcTypeExt, RunError, RunResult, SimpleException}, heap::{DropWithContext, HeapReadOutput}, - types::py_trait::attribute_name_value, value::{EitherStr, Value}, }; @@ -59,7 +58,7 @@ pub fn builtin_object_setattr(vm: &mut VM<'_>, args: ArgValues) -> RunResult, args: ArgValues) -> RunResult(value: &Value, vm: &'a VM<'_>) -> RunResult<&'a str> { - let opt = match value { - Value::InternBytes(bytes_id) => decode_utf8_path(vm.interns.get_bytes(*bytes_id))?, - Value::Ref(id) if let HeapData::Bytes(b) = vm.heap.get(*id) => decode_utf8_path(b.as_slice())?, - _ => value_as_path_str(value, vm.heap, vm.interns), +fn extract_path_string(value: &Value, vm: &VM<'_>) -> RunResult { + let path = match value.py_value(vm) { + PyValue::Str(text) => Some(text.as_str(vm).to_owned()), + PyValue::Bytes(bytes) => decode_utf8_path(bytes.as_slice(vm))?.map(str::to_owned), + _ => value_as_path_str(value, vm.heap, vm.interns).map(str::to_owned), }; - opt.ok_or_else(|| path_type_error(value, vm)) + path.ok_or_else(|| path_type_error(value, vm)) } /// Decodes a byte path as strict UTF-8, raising `UnicodeDecodeError` on @@ -209,18 +209,11 @@ fn validate_ignored_open_kwarg(name: &str, value: &Value, vm: &VM<'_>) -> Result "encoding" => { if matches!(value, Value::None) { true - } else if value.is_str(vm.heap) { - let s = match value { - Value::InternString(id) => vm.interns.get_str(*id), - Value::Ref(id) => match vm.heap.get(*id) { - HeapData::Str(s) => s.as_str(), - _ => "", - }, - _ => "", + } else { + let Some(s) = value.as_str(vm) else { + return Err(kwarg_type_error(name, value, vm)); }; s.eq_ignore_ascii_case("utf-8") || s.eq_ignore_ascii_case("utf8") - } else { - return Err(kwarg_type_error(name, value, vm)); } } // `errors` accepts str or None in CPython; only the default (None) diff --git a/crates/bashkit-monty/src/builtins/print.rs b/crates/bashkit-monty/src/builtins/print.rs index 777b9fa97..c65565bdb 100644 --- a/crates/bashkit-monty/src/builtins/print.rs +++ b/crates/bashkit-monty/src/builtins/print.rs @@ -54,8 +54,10 @@ pub fn builtin_print(vm: &mut VM<'_>, args: ArgValues) -> RunResult { defer_drop!(s, vm); // Resolve the `str` `Value` against the heap/interns tables directly so // the `&str` borrow stays disjoint from the `&mut vm.print_writer` write. - vm.print_writer - .write(stream, s.to_str_heap(vm.heap, vm.interns)?.into())?; + vm.print_writer.write( + stream, + s.as_str_heap(vm.heap, vm.interns).expect("py_str returns str").into(), + )?; } if let Some(end) = end_str { diff --git a/crates/bashkit-monty/src/builtins/reversed.rs b/crates/bashkit-monty/src/builtins/reversed.rs index 624e2f001..509154db9 100644 --- a/crates/bashkit-monty/src/builtins/reversed.rs +++ b/crates/bashkit-monty/src/builtins/reversed.rs @@ -55,7 +55,7 @@ pub fn builtin_reversed(vm: &mut VM<'_>, args: ArgValues) -> RunResult { /// dispatched, see `limitations/classes.md`. fn is_reversible(value: &Value, vm: &VM<'_>) -> bool { match value { - Value::InternString(_) | Value::InternBytes(_) => true, + Value::InternString(_) | Value::InlineString(_) | Value::InternBytes(_) => true, Value::Ref(id) => matches!( vm.heap.get(*id), HeapData::List(_) diff --git a/crates/bashkit-monty/src/builtins/type_.rs b/crates/bashkit-monty/src/builtins/type_.rs index 4bd4c940b..a7c8b1357 100644 --- a/crates/bashkit-monty/src/builtins/type_.rs +++ b/crates/bashkit-monty/src/builtins/type_.rs @@ -88,7 +88,12 @@ pub(crate) fn type_of_ref(vm: &mut VM<'_>, value: &Value) -> Value { vm.heap.inc_ref(class_id); Value::Ref(class_id) } else { - Value::Builtin(Builtins::Type(value.py_type(vm))) + Value::Builtin(Builtins::Type( + value + .py_type(vm) + .try_into() + .expect("instances return their class object"), + )) } } diff --git a/crates/bashkit-monty/src/bytecode/code.rs b/crates/bashkit-monty/src/bytecode/code.rs index 62f0f3845..3fd8d17a5 100644 --- a/crates/bashkit-monty/src/bytecode/code.rs +++ b/crates/bashkit-monty/src/bytecode/code.rs @@ -4,6 +4,8 @@ //! bytecode instructions, a constant pool, source location information for tracebacks, //! and an exception handler table. +use std::ops::Not; + use crate::{intern::StringId, parse::CodeRange, value::Value}; /// Compiled bytecode for a function or module. @@ -42,6 +44,11 @@ pub struct Code { /// messages when accessing undefined local variables (e.g., "name 'x' is not defined"). #[serde(rename = "N")] local_names: Vec, + + /// Whether the source ran under `from __future__ import annotations`: its + /// definitions store PEP 563 strings, and `exec()` here inherits the flag. + #[serde(rename = "U", default, skip_serializing_if = "Not::not")] + future_annotations: bool, } impl Code { @@ -68,9 +75,23 @@ impl Code { location_table, exception_table, local_names, + future_annotations: false, } } + /// Marks the code as compiled under `from __future__ import annotations`. + #[must_use] + pub(crate) fn with_future_annotations(mut self, future_annotations: bool) -> Self { + self.future_annotations = future_annotations; + self + } + + /// Whether the code was compiled under `from __future__ import annotations`. + #[must_use] + pub(crate) fn future_annotations(&self) -> bool { + self.future_annotations + } + /// Returns the raw bytecode bytes. #[must_use] pub fn bytecode(&self) -> &[u8] { @@ -111,6 +132,16 @@ impl Code { after.checked_sub(1).map(|index| &self.location_table[index]) } + /// Visits every source range in the location table, for a dump upgrade that rebases positions. + pub(crate) fn for_each_position_mut(&mut self, mut f: impl FnMut(&mut CodeRange)) { + for entry in &mut self.location_table { + f(&mut entry.range); + if let Some(focus) = &mut entry.focus { + f(focus); + } + } + } + /// Finds an exception handler for the given bytecode offset. /// /// Searches the exception table for an entry whose protected range contains @@ -133,6 +164,7 @@ impl Clone for Code { location_table: self.location_table.clone(), exception_table: self.exception_table.clone(), local_names: self.local_names.clone(), + future_annotations: self.future_annotations, } } } diff --git a/crates/bashkit-monty/src/bytecode/compiler.rs b/crates/bashkit-monty/src/bytecode/compiler.rs index a25b8bb3d..4e10f6888 100644 --- a/crates/bashkit-monty/src/bytecode/compiler.rs +++ b/crates/bashkit-monty/src/bytecode/compiler.rs @@ -21,7 +21,7 @@ use super::{ use crate::{ args::{ArgExprs, CallArg, CallKwarg, Kwarg}, builtins::{Builtins, BuiltinsFunctions}, - exception_private::{ExcType, RunError, SimpleException}, + exception_private::{ExcType, ExceptionRaise, RunError, SimpleException}, expressions::{ AssignTarget, Callable, CaptureSource, CmpOperator, Comprehension, DictItem, Expr, ExprLoc, Identifier, ImportName, Literal, NameScope, Node, Operator, PreparedFunctionDef, PreparedNode, SequenceItem, Submodule, @@ -29,7 +29,7 @@ use crate::{ }, fstring::{ConversionFlag, FStringPart, FormatSpec}, function::Function, - intern::{CompileInterns, StringId}, + intern::{CompileInterns, FunctionId, StaticStrings, StringId}, name_map::NameMap, namespace::NamespaceId, parse::{CodeRange, ExceptHandler, Try, syntax_error_in_snippet}, @@ -294,6 +294,10 @@ pub struct Compiler<'a, 'i> { /// Compiler settings inherited by nested scopes, with await restrictions reset for functions. #[derive(Debug, Clone, Copy)] +#[expect( + clippy::struct_excessive_bools, + reason = "independent switches copied into nested scopes" +)] struct ScopeFlags { /// Whether to compile pytest-style assert failure annotations. assert_message_annotations: bool, @@ -304,6 +308,9 @@ struct ScopeFlags { /// Rejects `await` at snippet top level and in its class bodies. /// Nested function bodies reset this restriction. forbid_await: bool, + /// Whether the compile unit runs under `from __future__ import annotations`, + /// stamped on every `Code` it produces. + future_annotations: bool, } /// Jump targets needed to compile `break` and `continue`. @@ -536,8 +543,9 @@ impl<'a, 'i> Compiler<'a, 'i> { interns: &mut CompileInterns<'_>, globals: &NameMap, options: CompileOptions, + future_annotations: bool, ) -> Result { - Self::compile_module_inner(nodes, interns, globals, options, None) + Self::compile_module_inner(nodes, interns, globals, options, None, future_annotations) } /// Compiles a prepared `eval()` / `exec()` snippet, rejecting top-level await. @@ -549,8 +557,16 @@ impl<'a, 'i> Compiler<'a, 'i> { globals: &NameMap, options: CompileOptions, globals_by_name: bool, + future_annotations: bool, ) -> Result { - Self::compile_module_inner(nodes, interns, globals, options, Some(globals_by_name)) + Self::compile_module_inner( + nodes, + interns, + globals, + options, + Some(globals_by_name), + future_annotations, + ) } /// Shared module compiler; `snippet` is `Some(globals_by_name)` for eval/exec. @@ -560,6 +576,7 @@ impl<'a, 'i> Compiler<'a, 'i> { globals: &NameMap, options: CompileOptions, snippet: Option, + future_annotations: bool, ) -> Result { check_namespace_size_u16(globals.len(), "module")?; // Module frames have `locals_count = 0` at runtime (globals live in @@ -569,6 +586,7 @@ impl<'a, 'i> Compiler<'a, 'i> { assert_message_annotations: options.assert_message_annotations.enabled(), globals_by_name: snippet.unwrap_or(false), forbid_await: snippet.is_some(), + future_annotations, }; let mut compiler = Compiler::new(interns, true, 0, flags); @@ -581,7 +599,12 @@ impl<'a, 'i> Compiler<'a, 'i> { compiler.code.emit(Opcode::LoadNone)?; compiler.code.emit(Opcode::ReturnValue)?; - Ok(compiler.code.build()) + Ok(compiler.finish()) + } + + /// Builds the compiled `Code`, stamped with the unit's `__future__` state. + fn finish(self) -> Code { + self.code.build().with_future_annotations(self.flags.future_annotations) } /// Compiles a function body to bytecode, appending any nested functions to `interns`. @@ -622,7 +645,7 @@ impl<'a, 'i> Compiler<'a, 'i> { compiler.code.emit(Opcode::LoadNone)?; compiler.code.emit(Opcode::ReturnValue)?; - Ok(compiler.code.build()) + Ok(compiler.finish()) } /// Compiles statements, retaining `finally` bodies for inline cleanup. @@ -767,14 +790,19 @@ impl<'a, 'i> Compiler<'a, 'i> { } => self.compile_for(target, iter, body, or_else)?, Node::While { test, body, or_else } => self.compile_while(test, body, or_else)?, Node::Assert { test, msg } => self.compile_assert(test, msg.as_ref())?, - Node::Raise(expr) => { - if let Some(exc) = expr { + Node::Raise { exc, cause } => match (exc, cause) { + (Some(exc), Some(cause)) => { + self.compile_expr(exc)?; + self.compile_expr(cause)?; + self.code.emit(Opcode::RaiseFrom)?; + } + (Some(exc), None) => { self.compile_expr(exc)?; self.code.emit(Opcode::Raise)?; - } else { - self.code.emit(Opcode::Reraise)?; } - } + // The parser rejects `raise from cause` without an exception. + (None, _) => self.code.emit(Opcode::Reraise)?, + }, Node::FunctionDef { def, decorators } => self.compile_function_def(def, decorators)?, Node::ClassDef { name, @@ -896,7 +924,13 @@ impl<'a, 'i> Compiler<'a, 'i> { let defaults_count = check_call_args_u8(func_def.default_exprs.len(), "default parameter values", func_pos)?; let cell_count = check_call_args_u8(func_def.free_var_enclosing_slots.len(), "closure variables", func_pos)?; - // 1. Compile the body recursively. + // 1. Compile the `__annotate__` function (PEP 649) and the body + // recursively; nested functions are pushed first, so they get lower ids. + let annotate = func_def + .annotate + .as_deref() + .map(|annotate| self.compile_annotate(annotate)) + .transpose()?; let namespace_size = check_namespace_size_u16(func_def.namespace_size, what)?; let body_code = compile_body(self.interns, namespace_size)?; @@ -914,7 +948,7 @@ impl<'a, 'i> Compiler<'a, 'i> { }) .collect(); let function = Function::new( - func_def.name, + self.function_name(func_def), func_def.signature.clone(), func_def.namespace_size, enclosing_slot_metadata, @@ -924,7 +958,8 @@ impl<'a, 'i> Compiler<'a, 'i> { func_def.default_exprs.len(), func_def.is_async, body_code, - ); + ) + .with_annotate(annotate); let func_id = self.interns.push_function(function); // 3. Compile and push default values (evaluated at definition time) @@ -960,6 +995,46 @@ impl<'a, 'i> Compiler<'a, 'i> { Ok(()) } + /// Compiles a `def`'s `__annotate__(format)` body and interns it, returning + /// its id for the owning [`Function`]. No `MakeFunction` is emitted: the + /// function value is built on `f.__annotate__` access from the owner's + /// globals, since it has no defaults or captured cells of its own. + fn compile_annotate(&mut self, annotate: &PreparedFunctionDef) -> Result { + debug_assert!( + annotate.free_var_enclosing_slots.is_empty() && annotate.default_exprs.is_empty(), + "an annotate function captures nothing and has no defaults" + ); + let namespace_size = check_namespace_size_u16(annotate.namespace_size, "annotate function")?; + let code = Self::compile_function_body(annotate, self.interns, namespace_size, self.flags)?; + let function = Function::new( + self.function_name(annotate), + annotate.signature.clone(), + annotate.namespace_size, + Vec::new(), + annotate.free_var_slots.clone(), + annotate.cell_var_slots.clone(), + annotate.cell_param_indices.clone(), + 0, + false, + code, + ); + let func_id = self.interns.push_function(function); + Ok(FunctionId::from_index(check_function_count_u16( + func_id, + annotate.name.position, + )?)) + } + + /// The name a function reports in tracebacks: a synthesized `__annotate__` is + /// called that, as in CPython, whatever a class body binds it as. + fn function_name(&mut self, func_def: &PreparedFunctionDef) -> Identifier { + let mut name = func_def.name; + if func_def.is_annotate { + name.name_id = self.interns.intern_static(StaticStrings::DunderAnnotate); + } + name + } + /// Compiles a `class Foo: ...` definition. /// /// Modelled on CPython's class-body code object: the class body is compiled @@ -1032,10 +1107,10 @@ impl<'a, 'i> Compiler<'a, 'i> { /// Compiles a class body, mirroring /// [`compile_function_body`](Self::compile_function_body) but replacing the /// implicit `LoadNone; ReturnValue` tail with a `type(name, (), {...})` - /// call: push the class name and an empty bases tuple, then for each - /// member (in source order) push `LoadConst ` and the member's value - /// from its class-body slot, build the namespace dict, and call the 3-arg - /// `type()` builtin (which builds the `Class`), then `ReturnValue`. + /// call: push the class name and an empty bases tuple, then for each member + /// (in source order) `LoadConst ` and the member's value from its + /// class-body slot, build the namespace dict, call the 3-arg `type()` + /// builtin (which builds the `Class`), then `ReturnValue`. /// /// Members are plain locals (the prepare phase forces class-body locals to /// never be cells — see `prepare_class_def`), so [`compile_name`](Self::compile_name) @@ -1077,7 +1152,7 @@ impl<'a, 'i> Compiler<'a, 'i> { .emit_call_builtin_function(BuiltinsFunctions::Type as u8, 3)?; compiler.code.emit(Opcode::ReturnValue)?; - Ok(compiler.code.build()) + Ok(compiler.finish()) } /// Compiles an import, resolving the module only when execution reaches it. @@ -1828,7 +1903,7 @@ impl<'a, 'i> Compiler<'a, 'i> { // - Callable must be a builtin type constructor (known at compile time) // - Arguments must be positional-only (Empty, One, Two, or Args) if let Callable::Builtin(Builtins::Type(t)) = callable - && let Some(type_id) = t.callable_to_u8() + && let Some(type_id) = Type::from(*t).callable_to_u8() && let Some(arg_count) = self.compile_builtin_call(args, call_pos)? { // Optimization applied - CallBuiltinType emitted @@ -2291,7 +2366,7 @@ impl<'a, 'i> Compiler<'a, 'i> { } Builtins::ExcType(exc_type) => self.interns.get_string_id_by_name(&exc_type.to_string())?, Builtins::Type(type_) => { - let name = type_.builtin_name()?; + let name = Type::from(type_).builtin_name()?; self.interns.get_string_id_by_name(name)? } }; @@ -4000,11 +4075,28 @@ impl CompileError { } } + /// Converts an imported file's compile error; see `ParseError::into_file_run_error`. + pub(crate) fn into_file_run_error(self, path: &str, source: &str) -> RunError { + let (exc_type, msg, frame) = self.into_parts(path, source); + RunError::Exc(ExceptionRaise { + exc: SimpleException::new_msg(exc_type, msg), + frame: None, + snippet_frame: Some(Box::new(frame)), + hide_caret: true, + }) + } + /// Converts this compile error into a Python exception. /// /// Syntax errors omit the frame name; unsupported constructs report a /// runtime-style location with the stored exception type and message. pub fn into_python_exc(self, filename: &str, source: &str) -> MontyException { + let (exc_type, msg, frame) = self.into_parts(filename, source); + MontyException::with_traceback(exc_type, Some(msg), vec![frame]) + } + + /// The exception type, message and the frame locating the error in `filename`. + fn into_parts(self, filename: &str, source: &str) -> (ExcType, String, StackFrame) { let mut source_map = SourceMap::new(source); let mut frame = if self.exc_type == ExcType::SyntaxError { // SyntaxError uses different format: no `, in ` @@ -4016,7 +4108,7 @@ impl CompileError { if self.exc_type == ExcType::ModuleNotFoundError { frame.hide_caret = true; } - MontyException::with_traceback(self.exc_type, Some(self.message.into_owned()), vec![frame]) + (self.exc_type, self.message.into_owned(), frame) } } diff --git a/crates/bashkit-monty/src/bytecode/mod.rs b/crates/bashkit-monty/src/bytecode/mod.rs index 502524cf1..bb9fe222d 100644 --- a/crates/bashkit-monty/src/bytecode/mod.rs +++ b/crates/bashkit-monty/src/bytecode/mod.rs @@ -26,7 +26,8 @@ pub use compiler::Compiler; pub(crate) use op::opcode_fingerprint; pub(crate) use op::{NAME_CALLABLE, NAME_GLOBAL_ONLY, Opcode}; pub(crate) use vm::{ - CallResult, ContainsVM, FrameNamespace, PendingLookupEffect, RecursionToken, RunReentryGuard, unpack_exact, + CallResult, ContainsVM, FrameGlobals, FrameNamespace, MissingNames, ModuleCache, PendingImport, + PendingLookupEffect, RecursionToken, RunReentryGuard, unpack_exact, }; pub use vm::{FrameExit, VM, VMSnapshot}; diff --git a/crates/bashkit-monty/src/bytecode/op.rs b/crates/bashkit-monty/src/bytecode/op.rs index e91dd2afd..8bdbafafe 100644 --- a/crates/bashkit-monty/src/bytecode/op.rs +++ b/crates/bashkit-monty/src/bytecode/op.rs @@ -405,7 +405,6 @@ pub enum Opcode { // Note: No SetupTry/PopExceptHandler - we use static exception_table /// Raise TOS as exception. Raise = 97, - // NOTE: RaiseFrom removed - `raise ... from ...` not supported by parser /// Re-raise current exception (bare `raise`). Reraise = 98, /// Clear current_exception when exiting except block. @@ -598,6 +597,9 @@ pub enum Opcode { /// becomes `[v, a, b, c]`. Operand: u8 n. The inverse of `LiftToTop`; the /// pattern compiler uses it to park a capture under the pattern's temporaries. SinkTop = 129, + /// `raise exc from cause`: stack `[exc, cause] -> []`. The cause becomes the + /// raised exception's `__cause__` and suppresses its `__context__`. + RaiseFrom = 130, } /// `LoadName` flag: the load is in call position, so an unresolved name under @@ -695,6 +697,7 @@ impl Opcode { | Self::StoreSubscr | Self::GetIter | Self::Raise + | Self::RaiseFrom | Self::Reraise | Self::ClearException | Self::CheckExcMatch @@ -962,6 +965,7 @@ impl Opcode { (StoreSubscr, Operand::None) => -3, (GetIter | Await, Operand::None) => 0, (Raise, Operand::None) => -1, + (RaiseFrom, Operand::None) => -2, (Reraise | ClearException | CheckExcMatch, Operand::None) => 0, (ReturnValue, Operand::None) => -1, (Nop, Operand::None) => 0, diff --git a/crates/bashkit-monty/src/bytecode/vm/async_exec.rs b/crates/bashkit-monty/src/bytecode/vm/async_exec.rs index 2823ab6a5..21f3297b2 100644 --- a/crates/bashkit-monty/src/bytecode/vm/async_exec.rs +++ b/crates/bashkit-monty/src/bytecode/vm/async_exec.rs @@ -916,6 +916,7 @@ impl<'h> VM<'h> { ExtFunctionResult::NotFound(function_name) => { self.fail_future(call_id, ExtFunctionResult::not_found_exc(&function_name)); } + ExtFunctionResult::ModuleFile(_) => self.fail_future(call_id, ExcType::module_file_for_non_import()), } } Ok(()) diff --git a/crates/bashkit-monty/src/bytecode/vm/attr.rs b/crates/bashkit-monty/src/bytecode/vm/attr.rs index 2715dfbc5..8f82f4f86 100644 --- a/crates/bashkit-monty/src/bytecode/vm/attr.rs +++ b/crates/bashkit-monty/src/bytecode/vm/attr.rs @@ -84,6 +84,7 @@ impl VM<'_> { } /// Loads a `from ... import` attribute, raising `ImportError` if missing. + /// A file package's missing attribute may be a submodule, imported here. /// `module_id` supplies the error's module name because host values need not be `Module`s. pub(super) fn load_attr_import(&mut self, name_id: StringId, module_id: StringId) -> Result { let this = self; @@ -95,8 +96,14 @@ impl VM<'_> { match obj.py_getattr(&attr, this) { Ok(result) => Ok(result), Err(RunError::Exc(exc)) if exc.exc.exc_type() == ExcType::AttributeError => { - let name_str = this.interns.get_str(name_id); - Err(ExcType::cannot_import_name(name_str, this.interns.get_str(module_id))) + this.import_file_attr(obj, name_id).unwrap_or_else(|| { + let name_str = this.interns.get_str(name_id); + Err(ExcType::cannot_import_name( + name_str, + this.interns.get_str(module_id), + None, + )) + }) } Err(e) => Err(e), } @@ -105,13 +112,17 @@ impl VM<'_> { /// Replaces the stack top with the next submodule of a dotted import. /// Missing attributes raise `ModuleNotFoundError` naming `path_id`. Modules also /// reject non-module attributes (`math.pi`, the host-served `os.environ`); bundled - /// ones add "is not a package" to errors, host modules being packages. + /// ones add "is not a package" to errors, host modules being packages. A file + /// package imports the submodule's own file, whatever attribute it has. pub(super) fn load_submodule(&mut self, name_id: StringId, path_id: StringId) -> Result { let this = self; let obj = this.pop(); defer_drop!(obj, this); + if let Some(result) = this.import_file_submodule(obj, path_id) { + return result; + } let package = module_package(obj, this.heap); let is_builtin = package == Some(false); let attr = EitherStr::Interned(name_id); diff --git a/crates/bashkit-monty/src/bytecode/vm/binary.rs b/crates/bashkit-monty/src/bytecode/vm/binary.rs index f86f729c1..77823ced6 100644 --- a/crates/bashkit-monty/src/bytecode/vm/binary.rs +++ b/crates/bashkit-monty/src/bytecode/vm/binary.rs @@ -41,6 +41,11 @@ impl VM<'_> { self.binary_op(|lhs, rhs, vm| lhs.py_mul(rhs, vm)) } + /// Tries in-place multiplication, then binary fallback; reflected results may replace the operand. + pub(super) fn inplace_mult(&mut self) -> Result<(), RunError> { + self.inplace_op(PyTrait::py_imul_impl, |lhs, rhs, vm| lhs.py_mul(rhs, vm)) + } + /// Binary division. pub(super) fn binary_div(&mut self) -> Result<(), RunError> { self.binary_op(|lhs, rhs, vm| lhs.py_truediv(rhs, vm)) @@ -77,6 +82,11 @@ impl VM<'_> { self.binary_op(|lhs, rhs, vm| lhs.py_xor(rhs, vm)) } + /// Set symmetric difference mutates the left operand before binary fallback. + pub(super) fn inplace_xor(&mut self) -> Result<(), RunError> { + self.inplace_op(PyTrait::py_ixor_impl, |lhs, rhs, vm| lhs.py_xor(rhs, vm)) + } + /// Binary left shift. pub(super) fn binary_lshift(&mut self) -> Result<(), RunError> { self.binary_op(|lhs, rhs, vm| lhs.py_lshift(rhs, vm)) @@ -169,9 +179,9 @@ impl VM<'_> { /// Applies an in-place operation, offering the left operand `inplace` (its /// `py_i*_impl` hook) first and otherwise falling back to `binary`. /// - /// A hook reporting `true` has mutated the left operand, which is pushed - /// back so it keeps its identity; `false` means the type has no in-place - /// form and the ordinary binary operator produces a fresh value. + /// A handled operation pushes the updated left operand: native mutation keeps + /// its identity, while reflected arithmetic may replace it. Otherwise the + /// ordinary binary operator produces the result. fn inplace_op( &mut self, inplace: impl FnOnce(&mut Value, &Value, &mut Self) -> RunResult, diff --git a/crates/bashkit-monty/src/bytecode/vm/call.rs b/crates/bashkit-monty/src/bytecode/vm/call.rs index 03fc31fa9..b211bb880 100644 --- a/crates/bashkit-monty/src/bytecode/vm/call.rs +++ b/crates/bashkit-monty/src/bytecode/vm/call.rs @@ -8,7 +8,10 @@ use std::mem; use monty_types::{MontyUuid, OsFunctionCall}; -use super::{CallFrame, VM, attr::PendingLookupEffect, function_namespace, recursion::RunReentryGuard}; +use super::{ + CallFrame, FrameGlobals, FrameNamespace, MissingNames, VM, attr::PendingLookupEffect, function_namespace, + recursion::RunReentryGuard, +}; use crate::{ args::{ArgValues, KwargsValues}, asyncio::Coroutine, @@ -891,7 +894,91 @@ impl<'h> VM<'h> { if func.is_async { self.create_coroutine(func_id, func, cells, defaults, globals, args) } else { - self.call_sync_function(func_id, func, cells, defaults, globals, args) + let namespace = function_namespace(globals, &*self.heap); + self.call_sync_function(func_id, func, cells, defaults, namespace, args) + } + } + + /// Calls an `__annotate__` function with `format` (PEP 649). + /// + /// A `def` runs under [`FrameNamespace::Annotate`]: names resolve through + /// `classdict` (a borrowed class-namespace copy, for a class's annotations), + /// then its globals, with `missing` standing in for CPython's "fake globals" + /// in `FORWARDREF` and `STRING` format. Any other callable runs plainly. + /// Takes ownership of `missing`. + pub(crate) fn call_annotate( + &mut self, + annotate: &Value, + format: i64, + classdict: Option, + missing: MissingNames, + ) -> Result { + let this = self; + let args = ArgValues::One(Value::Int(format)); + // The guard releases `missing` on the paths that run without a namespace. + let mut missing_guard = DropGuard::new(missing, this); + let (_, this) = missing_guard.as_parts_mut(); + let Some(FunctionParts { + func_id, + cells, + defaults, + globals, + }) = this.function_parts(annotate) + else { + return this.call_function(annotate, args); + }; + let func = this.interns.get_function(func_id); + if func.is_async { + defer_drop!(defaults, this); + return this.create_coroutine(func_id, func, &cells, defaults, globals, args); + } + let (missing, this) = missing_guard.into_parts(); + defer_drop!(defaults, this); + let globals = match globals { + Some(dict) => { + this.heap.inc_ref(dict); + FrameGlobals::Dict(dict) + } + None => FrameGlobals::Slots, + }; + if let Some(dict) = classdict { + this.heap.inc_ref(dict); + } + let namespace = Box::new(FrameNamespace::Annotate { + globals, + classdict, + missing, + }); + this.call_sync_function(func_id, func, &cells, defaults, Some(namespace), args) + } + + /// The [`FunctionParts`] of a Python function value; `None` for a callable + /// that is not a `def` (a builtin, a bound method, ...). + fn function_parts(&self, value: &Value) -> Option { + let parts = |func_id, cells, defaults: &[Value], globals| FunctionParts { + func_id, + cells, + defaults: defaults.iter().map(|v| v.clone_with_heap(self)).collect(), + globals, + }; + match value { + Value::DefFunction(func_id) => Some(parts(*func_id, Box::default(), &[], None)), + Value::Ref(id) => match self.heap.get(*id) { + HeapData::FunctionDefaults(function) => Some(parts( + function.func_id, + Box::default(), + &function.defaults, + function.globals, + )), + HeapData::Closure(closure) => Some(parts( + closure.func_id, + closure.cells.clone(), + &closure.defaults, + closure.globals, + )), + _ => None, + }, + _ => None, } } @@ -968,7 +1055,8 @@ impl<'h> VM<'h> { /// Calls a sync function by pushing a new frame. /// /// Sets up the function's namespace with bound arguments, cell variables, - /// and free variables (captured from enclosing scope for closures). + /// and free variables (captured from enclosing scope for closures), and + /// installs `frame_namespace` (owned; released here if binding fails). /// /// Locals are built in the reusable `namespace_scratch` buffer (under a /// [`DropGuard`] for cleanup on error) and moved onto the VM stack, where @@ -979,7 +1067,7 @@ impl<'h> VM<'h> { func: &'h Function, cells: &[HeapId], defaults: &[Value], - globals: Option, + frame_namespace: Option>, args: ArgValues, ) -> Result { let call_offset = self.current_offset(); @@ -988,25 +1076,24 @@ impl<'h> VM<'h> { let namespace_size = func.namespace_size; let locals_count = u16::try_from(namespace_size).expect("function namespace size exceeds u16"); + let mut frame_namespace_guard = DropGuard::new(frame_namespace, self); + let (_, this) = frame_namespace_guard.as_parts_mut(); + // 1. Build the namespace in the reusable scratch buffer to avoid a // per-call allocation. On error `DropGuard` drops the buffer, so the // pool just restarts empty next call. - let mut namespace = mem::take(&mut self.namespace_scratch); + let mut namespace = mem::take(&mut this.namespace_scratch); namespace.reserve(namespace_size); - let mut namespace_guard = DropGuard::new(namespace, self); + let mut namespace_guard = DropGuard::new(namespace, this); let (namespace, this) = namespace_guard.as_parts_mut(); // 2. Bind arguments to parameters - { - let bind_result = func.signature.bind(args, defaults, this, func.name, namespace); - - bind_result?; - } + func.signature.bind(args, defaults, this, func.name, namespace)?; // 3. Install owned cells and captured free-var cells at their slots. this.install_closure_cells(func, cells, namespace); - // 6. Commit the guard (no rollback) and push the frame. The operand + // 4. Commit the guards (no rollback) and push the frame. The operand // stack starts immediately above the locals region — comprehensions // emit their own push/pop bytecode, so no frame-level region is // reserved here. `append` empties the buffer (keeping its allocation) @@ -1014,9 +1101,9 @@ impl<'h> VM<'h> { let (mut namespace, this) = namespace_guard.into_parts(); this.stack.append(&mut namespace); this.namespace_scratch = namespace; + let (frame_namespace, this) = frame_namespace_guard.into_parts(); let exc_stack_base = this.exception_stack.len(); - let namespace = function_namespace(globals, &*this.heap); this.push_frame(CallFrame::new_function( &func.code, stack_base, @@ -1024,7 +1111,7 @@ impl<'h> VM<'h> { exc_stack_base, func_id, call_offset, - namespace, + frame_namespace, ))?; Ok(CallResult::FramePushed) @@ -1281,3 +1368,13 @@ fn dispatch_exit(heap_id: HeapId, vm: &mut VM<'_>, args: ArgValues) -> Result, + /// OWNED clones, released by the caller. + defaults: Vec, + globals: Option, +} diff --git a/crates/bashkit-monty/src/bytecode/vm/collections.rs b/crates/bashkit-monty/src/bytecode/vm/collections.rs index 572f297f5..cb89057a3 100644 --- a/crates/bashkit-monty/src/bytecode/vm/collections.rs +++ b/crates/bashkit-monty/src/bytecode/vm/collections.rs @@ -6,6 +6,7 @@ use crate::{ exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, heap::{DropGuard, DropWithContext, Heap, HeapData, HeapReadOutput}, intern::StringId, + resource_checks::check_estimated_size, types::{ Dict, List, PyTrait, Set, Slice, allocate_tuple, collect_iterable, collect_iterable_bounded, instance::instance_defines_iter, slice::value_to_option_i64, @@ -41,7 +42,13 @@ impl VM<'_> { let this = self; let items = this.pop_n(count * 2).into_iter(); defer_drop_mut!(items, this); - let mut dict_guard = DropGuard::new(Dict::new(), this); + + // Estimate keys, values, hashes and index storage, including unused buckets. + let entry_bytes = 2 * VALUE_SIZE + size_of::() + 3 * size_of::(); + check_estimated_size(count.saturating_mul(entry_bytes), &this.heap.tracker)?; + + // Exact sizing avoids spare slots; for example, five pairs would otherwise reserve eight. + let mut dict_guard = DropGuard::new(Dict::with_capacity(count), this); loop { let (dict, this) = dict_guard.as_parts_mut(); let (Some(key), Some(value)) = (items.next(), items.next()) else { @@ -248,30 +255,15 @@ impl VM<'_> { let copied_items = copied_items.into_iter(); defer_drop_mut!(copied_items, this); for (key, value) in copied_items { - // Validate key is a string (InternString or heap-allocated Str) - let is_string = match &key { - Value::InternString(_) => true, - Value::Ref(id) => matches!(this.heap.get(*id), HeapData::Str(_)), - _ => false, - }; - if !is_string { - key.drop_with(this); - value.drop_with(this); - return Err(ExcType::type_error_kwargs_nonstring_key()); - } - - // Get the string key for error messages (needed before moving key into closure) - let key_str = match &key { - Value::InternString(id) => this.interns.get_str(*id).to_string(), - Value::Ref(id) => { - if let HeapData::Str(s) = this.heap.get(*id) { - s.as_str().to_string() - } else { - "".to_string() - } - } - _ => "".to_string(), - }; + let mut pair_guard = DropGuard::new((key, value), this); + let (pair, this) = pair_guard.as_parts(); + // Borrow string keys uniformly across their storage forms. + let key_str = pair + .0 + .as_str(this) + .ok_or_else(ExcType::type_error_kwargs_nonstring_key)? + .to_owned(); + let ((key, value), this) = pair_guard.into_parts(); let HeapReadOutput::Dict(dict) = this.heap.read(dict_id) else { unreachable!("DictMerge: entry is not a Dict") diff --git a/crates/bashkit-monty/src/bytecode/vm/exceptions.rs b/crates/bashkit-monty/src/bytecode/vm/exceptions.rs index b655aa6b6..144abe21f 100644 --- a/crates/bashkit-monty/src/bytecode/vm/exceptions.rs +++ b/crates/bashkit-monty/src/bytecode/vm/exceptions.rs @@ -2,13 +2,15 @@ use std::fmt::{self, Write}; +use monty_types::ResourceError; + use super::VM; use crate::{ builtins::Builtins, defer_drop, exception_private::{ExcType, ExcTypeExt, ExceptionRaise, RawStackFrame, RunError, RunResult, SimpleException}, expressions::CmpOperator, - heap::{ContainsHeap, DropGuard, DropWithContext, HeapData}, + heap::{ContainsHeap, DropGuard, DropWithContext, HeapData, HeapId, HeapReadOutput}, intern::{StaticStrings, StringId}, types::{LazyHeapSet, PyTrait, Type}, value::Value, @@ -145,6 +147,127 @@ impl VM<'_> { }) } + /// Runs `raise exc from cause`. + /// + /// `exc` is checked first, as in CPython, then `cause` must be `None`, an + /// exception or an exception class (instantiated without a message). The + /// raised object records the cause and suppresses its context; a bare class + /// is instantiated here so there is an object to record it on. + pub(super) fn raise_with_cause(&mut self, exc: Value, cause: Value) -> Option { + let error = self.make_exception(&exc, true); + let raised = match self.exception_object(exc) { + Ok(raised) => raised, + Err(other) => { + // `error` is the `exceptions must derive from BaseException` TypeError. + other.drop_with(self); + cause.drop_with(self); + return self.handle_exception_with_value(error, None); + } + }; + let cause = match cause { + Value::None => None, + other => match self.exception_object(other) { + Ok(cause) => cause.into_ref_id(), + Err(other) => { + other.drop_with(self); + raised.drop_with(self); + let error = ExcType::type_error("exception causes must derive from BaseException"); + return self.handle_exception_with_value(error, None); + } + }, + }; + let Value::Ref(raised_id) = &raised else { + unreachable!("exceptions are heap values") + }; + self.set_exception_cause(*raised_id, cause); + self.handle_exception_with_value(error, Some(raised)) + } + + /// The exception object `value` denotes: itself for an exception, a fresh + /// instance for an exception class. Anything else comes back as `Err` for the + /// caller to release and report. + fn exception_object(&mut self, value: Value) -> Result { + match value { + Value::Ref(id) if matches!(self.heap.get(id), HeapData::Exception(_)) => Ok(value), + Value::Builtin(Builtins::ExcType(exc_type)) => Ok(self.allocate_exception(exc_type)), + other => Err(other), + } + } + + /// Allocates `exc_type()` with no message, for `raise ExcType from ...` and its cause. + fn allocate_exception(&mut self, exc_type: ExcType) -> Value { + Value::Ref( + self.heap + .allocate(HeapData::Exception(SimpleException::new_none(exc_type))), + ) + } + + /// Stores `cause` (an owned reference) as `__cause__` of the exception `id`, + /// releasing any previous cause, and sets `__suppress_context__`. + fn set_exception_cause(&mut self, id: HeapId, cause: Option) { + let previous = match self.heap.read(id) { + HeapReadOutput::Exception(exc) => exc.get_mut(self.heap).set_cause(cause), + _ => unreachable!("set_exception_cause is only called on exceptions"), + }; + previous.map(Value::Ref).drop_with(self); + } + + /// Records the exception being handled as `__context__` of the newly raised + /// `raised`, as CPython's `_PyErr_SetObject` does: a bare `raise` of the handled + /// exception itself gets none, and a link that would make the chain circular is + /// cut first. An internal (frozen) handler's exception is skipped, since the + /// equivalent CPython code is C and leaves the user's handled exception in place. + fn attach_context(&mut self, raised: &Value) -> Result<(), ResourceError> { + let handled = self.exception_stack.iter().rev().find_map(|caught| match caught { + CaughtException::Value(Value::Ref(id)) => Some(*id), + _ => None, + }); + let Some(handled_id) = handled else { + return Ok(()); + }; + let Value::Ref(raised_id) = raised else { + return Ok(()); + }; + if *raised_id == handled_id { + return Ok(()); + } + // Each re-raise inside a handler adds a link, so an unchecked scan of a + // chain grown by a loop would be quadratic: poll the clock. + let mut cursor = handled_id; + for step in 0usize.. { + let Some(next) = self.exception_context(cursor) else { + break; + }; + if next == *raised_id { + self.set_exception_context(cursor, None); + break; + } + self.heap.tracker.check_time_every(step)?; + cursor = next; + } + self.heap.inc_ref(handled_id); + self.set_exception_context(*raised_id, Some(handled_id)); + Ok(()) + } + + /// The `__context__` of the exception `id`, borrowed. + fn exception_context(&self, id: HeapId) -> Option { + match self.heap.get(id) { + HeapData::Exception(exc) => exc.context(), + _ => None, + } + } + + /// Stores `context` (an owned reference) as `__context__` of the exception + /// `id`, releasing any previous context. + fn set_exception_context(&mut self, id: HeapId, context: Option) { + let previous = match self.heap.read(id) { + HeapReadOutput::Exception(exc) => exc.get_mut(self.heap).set_context(context), + _ => unreachable!("set_exception_context is only called on exceptions"), + }; + previous.map(Value::Ref).drop_with(self); + } + /// Re-raises the active exception without replacing a user traceback with an internal handler. pub(super) fn reraise_exception(&mut self) -> (RunError, Option) { if let Some(caught) = self.exception_stack.last() { @@ -341,6 +464,10 @@ impl VM<'_> { }; self.create_exception_value(exc) }; + if let Err(error) = self.attach_context(&exc_value) { + exc_value.drop_with(self); + return ExceptionHandlingResult::Unhandled(self.unwind_for_traceback(error.into())); + } // Use DropGuard because exc_value is conditionally consumed (pushed onto // exception_stack when handler found) or dropped (when no handler found) @@ -433,9 +560,13 @@ impl VM<'_> { // This is where the caller invoked the function that's failing. let call_offset = this.current_frame().call_offset; + // A raising module body must not stay cached; checked before the pop. + let is_initializer = this.current_frame().is_initializer; // Synchronous evaluation stops unwinding here, but its caller still // belongs in the traceback when the error crosses that boundary. let should_return = this.pop_frame(); + // CPython shows no carets under the `import` a module body's error unwinds through. + let from_module_body = is_initializer && this.forget_failed_module(); // Add caller frame info to traceback (if we have a call site). // Resolve the offset now — against the caller, which is the current @@ -446,8 +577,8 @@ impl VM<'_> { let pos = this.resolve_offset(off); let frame_name = this.current_frame_name(); match &mut error { - RunError::Exc(exc) => exc.add_caller_frame(pos, frame_name), - RunError::UncatchableExc(exc) => exc.add_caller_frame(pos, frame_name), + RunError::Exc(exc) => exc.add_caller_frame(pos, frame_name, from_module_body), + RunError::UncatchableExc(exc) => exc.add_caller_frame(pos, frame_name, from_module_body), RunError::Internal(_) => {} } } @@ -465,7 +596,10 @@ impl VM<'_> { // Get the caller's call-site offset before popping frame let call_offset = self.current_frame().call_offset; + let is_initializer = self.current_frame().is_initializer; let should_return = self.pop_frame(); + // CPython shows no carets under the `import` a module body's error unwinds through. + let from_module_body = is_initializer && self.forget_failed_module(); // Add caller frame info to traceback. Resolve the offset against the // caller, which is the current frame after the pop above. @@ -475,8 +609,8 @@ impl VM<'_> { let pos = self.resolve_offset(off); let frame_name = self.current_frame_name(); match &mut error { - RunError::Exc(exc) => exc.add_caller_frame(pos, frame_name), - RunError::UncatchableExc(exc) => exc.add_caller_frame(pos, frame_name), + RunError::Exc(exc) => exc.add_caller_frame(pos, frame_name, from_module_body), + RunError::UncatchableExc(exc) => exc.add_caller_frame(pos, frame_name, from_module_body), RunError::Internal(_) => {} } } @@ -584,7 +718,7 @@ fn assert_operand_repr(value: &Value, vm: &mut VM<'_>) -> RunResult { fn assert_msg_str(value: &Value, vm: &mut VM<'_>) -> RunResult { let str_value = value.py_str(vm)?; defer_drop!(str_value, vm); - Ok(str_value.to_str(vm)?.to_owned()) + Ok(str_value.as_str(vm).expect("py_str returns str").to_owned()) } /// Byte-capped sink that stops repr formatting on a character boundary. diff --git a/crates/bashkit-monty/src/bytecode/vm/format.rs b/crates/bashkit-monty/src/bytecode/vm/format.rs index 7d101ae7e..c4a7a50a6 100644 --- a/crates/bashkit-monty/src/bytecode/vm/format.rs +++ b/crates/bashkit-monty/src/bytecode/vm/format.rs @@ -6,12 +6,12 @@ use super::VM; use crate::{ bytecode::op::{FORMAT_VALUE_HAS_SPEC, FORMAT_VALUE_STATIC_SPEC}, defer_drop, - exception_private::{ExcType, RunError, SimpleException}, + exception_private::{ExcType, ExcTypeExt, RunError, SimpleException}, fstring::{ ParseFormatSpecReason, ParsedFormatSpec, decode_format_spec, format_string, format_with_spec, validate_string_spec, }, - heap::HeapReadOutput, + heap::{HeapData, HeapReadOutput}, intern::StringId, string_builder::StringBuilder, types::{ @@ -42,7 +42,9 @@ impl VM<'_> { let mut total_len = 0_usize; for part in parts.as_slice() { - let s = part.to_str_heap(this.heap, this.interns)?; + let s = part + .as_str_heap(this.heap, this.interns) + .expect("f-string parts are strings"); total_len = total_len.saturating_add(s.len()); } @@ -50,7 +52,9 @@ impl VM<'_> { let mut result = String::with_capacity(total_len); for part in parts.as_slice() { - let s = part.to_str_heap(this.heap, this.interns)?; + let s = part + .as_str_heap(this.heap, this.interns) + .expect("f-string parts are strings"); result.push_str(s); } @@ -85,7 +89,8 @@ impl VM<'_> { let spec = decode_format_spec(*encoded); this.format_parsed_value(value, conversion, &spec)? } else { - let spec = str_value_into_string(spec_value.py_str(this)?, this)?; + // The compiler builds dynamic specs from f-string parts, which are strings. + let spec = spec_value.as_str(this).expect("format spec is a string").to_owned(); this.format_runtime_value(value, conversion, Some(&spec))? } } @@ -111,18 +116,21 @@ impl VM<'_> { } else { Ok(converted) } - } else if let Some(format_spec) = format_spec { - if let Some(formatted) = self.try_format_temporal(value, format_spec)? { - Ok(formatted) - } else if let Some(formatted) = self.try_format_decimal(value, format_spec)? { - Ok(formatted) + } else { + self.reject_stringifier(value)?; + if let Some(format_spec) = format_spec { + if let Some(formatted) = self.try_format_temporal(value, format_spec)? { + Ok(formatted) + } else if let Some(formatted) = self.try_format_decimal(value, format_spec)? { + Ok(formatted) + } else { + let value_type = value.py_type_name(self); + let spec = self.parse_runtime_spec(format_spec, &value_type)?; + self.format_parsed_value(value, 0, &spec) + } } else { - let value_type = value.py_type_name(self); - let spec = self.parse_runtime_spec(format_spec, &value_type)?; - self.format_parsed_value(value, 0, &spec) + self.convert_value(value, 0) } - } else { - self.convert_value(value, 0) } } @@ -140,6 +148,7 @@ impl VM<'_> { spec: &ParsedFormatSpec, ) -> Result { if conversion == 0 { + self.reject_stringifier(value)?; // Only a `Decimal` needs the spec back as text; checking first keeps the // render off every other value's path. if decimal::py::as_decimal(value, self).is_some() @@ -154,6 +163,22 @@ impl VM<'_> { } } + /// CPython's `_Stringifier.__format__` error: an f-string cannot render an + /// unresolved name while a `FORWARDREF` annotation evaluation composes text. + /// A `!r` / `!s` / `!a` conversion goes through the stringifier's repr instead, + /// which is its text, so only the unconverted paths check this. + fn reject_stringifier(&self, value: &Value) -> Result<(), RunError> { + if matches!(value, Value::Ref(id) if matches!(self.heap.get(*id), HeapData::ForwardRef(r) if r.is_stringifier())) + && self.in_forward_ref_evaluation() + { + Err(ExcType::type_error( + "Cannot stringify annotation containing string formatting", + )) + } else { + Ok(()) + } + } + /// Formats a string from a parsed format spec. fn format_parsed_string(&self, value: &str, spec: &ParsedFormatSpec) -> Result { validate_string_spec(spec)?; @@ -163,10 +188,12 @@ impl VM<'_> { /// Applies the f-string and `str.format()` conversion flags to a value. pub(crate) fn convert_value(&mut self, value: &Value, conversion: u8) -> Result { match conversion { - 0 | 1 if value.py_type(self) == Type::Str => Ok(value.to_str(self)?.to_owned()), - 2 => str_value_into_string(value.py_repr(self)?, self), + 0 | 1 if value.py_type(self) == Type::Str => { + Ok(value.as_str(self).expect("string type checked above").to_owned()) + } + 2 => Ok(str_value_into_string(value.py_repr(self)?, self)), 3 => { - let value = str_value_into_string(value.py_repr(self)?, self)?; + let value = str_value_into_string(value.py_repr(self)?, self); let mut escaped = StringBuilder::with_capacity(value.len(), &self.heap.tracker)?; for (index, character) in value.chars().enumerate() { self.heap.tracker.check_time_every(index)?; @@ -189,7 +216,7 @@ impl VM<'_> { escaped.finish_raw() } // No conversion and `!s` both use `str()`. - _ => str_value_into_string(value.py_str(self)?, self), + _ => Ok(str_value_into_string(value.py_str(self)?, self)), } } @@ -282,7 +309,7 @@ impl VM<'_> { /// `String`, dropping the value's heap reference on every path. Used by the /// f-string conversion arms, which need the text in an owned buffer to feed /// the mini-language formatter. -fn str_value_into_string(value: Value, vm: &mut VM<'_>) -> Result { +fn str_value_into_string(value: Value, vm: &mut VM<'_>) -> String { defer_drop!(value, vm); - Ok(value.to_str(vm)?.to_owned()) + value.as_str(vm).expect("py_str and py_repr return str").to_owned() } diff --git a/crates/bashkit-monty/src/bytecode/vm/mod.rs b/crates/bashkit-monty/src/bytecode/vm/mod.rs index 186ddf341..6a8750b5a 100644 --- a/crates/bashkit-monty/src/bytecode/vm/mod.rs +++ b/crates/bashkit-monty/src/bytecode/vm/mod.rs @@ -12,6 +12,8 @@ mod compare; mod context_manager; mod exceptions; mod format; +mod module_cache; +mod module_finder; mod namespace; mod pattern; mod recursion; @@ -23,8 +25,10 @@ pub(crate) use attr::PendingLookupEffect; pub(crate) use call::CallResult; pub(crate) use collections::unpack_exact; use exceptions::CaughtException; +pub(crate) use module_cache::ModuleCache; +pub(crate) use module_finder::PendingImport; use monty_types::{InvalidInputError, MontyObject, MontyUuid, OsFunctionCall, PrintWriter, SourceRange}; -pub(crate) use namespace::{FrameNamespace, function_namespace}; +pub(crate) use namespace::{FrameGlobals, FrameNamespace, MissingNames, function_namespace}; use recursion::frame_recursion_depth; pub(crate) use recursion::{ContainsVM, RecursionToken, RunReentryGuard}; use scheduler::Scheduler; @@ -52,8 +56,8 @@ use crate::{ name_map::NameMap, object_bridge::MontyObjectExt, os_dispatch::{ - PendingEffect, PostConversionEffect, PreConversionEffect, Reshaped, release_pending_effect, resolve_call_paths, - urandom_reply_error, + PendingEffect, PostConversionEffect, PreConversionEffect, Reshaped, check_raw_call_paths, + release_pending_effect, resolve_call_paths, urandom_reply_error, }, parse::CodeRange, run::{Program, SessionTables, VmEnv}, @@ -349,13 +353,14 @@ pub struct CallFrame<'code> { /// `cleanup_frame_state`, or taken by `serialize` for a snapshot. namespace: Option>, - /// Whether this frame is a class `__init__` running for `Foo(...)`. + /// Whether this frame is a class `__init__` running for `Foo(...)`, or the + /// body of a module imported from a file. /// /// When `true`, the `ReturnValue` handler discards the frame's return value - /// (`__init__` returns `None`) and leaves the instance — pushed onto the - /// caller's operand stack before this frame was created — as the result of the - /// construction. Threaded through serialization (`SerializedFrame`) so a - /// suspended initializer resumes correctly. + /// (`None`) and leaves the instance or module — pushed onto the caller's + /// operand stack before this frame was created — as the result of the + /// construction or import. Threaded through serialization (`SerializedFrame`) + /// so a suspended initializer resumes correctly. is_initializer: bool, /// Module name for `LoadAttrImport` errors, set by `LoadModule`/`LoadSubmodule`. @@ -591,7 +596,7 @@ pub struct SerializedFrame { #[serde(rename = "C")] call_offset: Option, - /// Whether this frame is a class `__init__` (see `CallFrame.is_initializer`). + /// Whether this frame is a class `__init__` or an imported module body (see `CallFrame.is_initializer`). /// /// Unlike `should_return`, an initializer frame can legitimately be live /// across a suspend (an `__init__` that calls an external/OS function), so it @@ -684,16 +689,28 @@ pub struct VMSnapshot { cwd: String, /// The session's `random` state at the pause. random: SessionRandom, + /// The session's file modules at the pause. + #[serde(default)] + modules: ModuleCache, +} + +/// What an abandoned snapshot hands back to its REPL session: the state that +/// outlives a snippet. +pub(crate) struct AbandonedState { + pub globals: Vec, + pub cwd: String, + pub random: SessionRandom, + pub modules: ModuleCache, } impl VMSnapshot { /// Discards the in-flight execution state of a snapshot that will never be /// restored, releasing every heap reference it holds (operand and exception /// stacks, scheduler tasks, pending resume effects), and returns the - /// globals, working directory and `random` generator so an abandoned REPL - /// snippet keeps its namespace, any `os.chdir` it made and any seed it - /// set. Mirrors `VM::drop`. - pub(crate) fn abandon(self, heap: &mut Heap) -> (Vec, String, SessionRandom) { + /// globals, working directory, `random` generator and file modules so an + /// abandoned REPL snippet keeps its namespace, any `os.chdir` it made, any + /// seed it set and any module it finished importing. Mirrors `VM::drop`. + pub(crate) fn abandon(self, heap: &mut Heap) -> AbandonedState { let Self { stack, globals, @@ -704,6 +721,7 @@ impl VMSnapshot { pending_lookup_effect, cwd, random, + mut modules, .. } = self; HeapReader::with(heap, &mut (), |heap, ()| { @@ -715,8 +733,15 @@ impl VMSnapshot { frame.namespace.drop_with(heap); } scheduler.cleanup(heap); + // a module body interrupted here must run again at the next import + modules.remove_unfinished(heap); }); - (globals, cwd, random) + AbandonedState { + globals, + cwd, + random, + modules, + } } /// Number of tasks the scheduler held when this snapshot was taken. @@ -858,6 +883,9 @@ pub struct VM<'h> { /// Preserved across snapshots and REPL feeds, including `random.seed()` changes. pub(crate) random: SessionRandom, + /// Modules imported from files, preserved across snapshots and REPL feeds. + pub(crate) modules: ModuleCache, + /// Working directory, `__file__` inputs and the assert-repr cap for this /// run. Rebuilt from the executor on restore, except the working /// directory, which travels in the snapshot because `os.chdir` may have @@ -900,6 +928,7 @@ impl<'h> VM<'h> { run_reentry_depth: recursion::MAX_RUN_REENTRY_DEPTH, re_pattern_cache: RePatternCache::default(), random: SessionRandom::default(), + modules: ModuleCache::default(), env: program.vm_env(), } } @@ -971,6 +1000,7 @@ impl<'h> VM<'h> { run_reentry_depth: recursion::MAX_RUN_REENTRY_DEPTH, re_pattern_cache: RePatternCache::default(), random: snapshot.random, + modules: snapshot.modules, env: { let mut env = program.vm_env(); env.cwd = Cow::Owned(snapshot.cwd); @@ -1027,6 +1057,7 @@ impl<'h> VM<'h> { // string), so a later `take_changed_cwd` on this VM stays honest. cwd: mem::replace(&mut self.env.cwd, Cow::Borrowed(self.env.initial_cwd)).into_owned(), random: mem::take(&mut self.random), + modules: mem::take(&mut self.modules), } } @@ -1057,23 +1088,23 @@ impl<'h> VM<'h> { } } - /// Joins paths to cwd and rejects NUL bytes before yielding an OS call. + /// Rejects NUL-byte and empty paths, then joins the rest to cwd before yielding an OS call. /// Rejected calls release their pending effect; existence predicates finish locally. fn prepare_os_call( &mut self, mut call: OsFunctionCall, effect: Option, ) -> RunResult> { - resolve_call_paths(&mut call, &self.env.cwd); - if let Err(message) = call.check_path_null_bytes() { + if let Err(err) = check_raw_call_paths(&call) { release_pending_effect(effect, self.heap); if call.is_existence_check() { self.push(Value::Bool(false)); Ok(None) } else { - Err(ExcType::value_error(message)) + Err(err) } } else { + resolve_call_paths(&mut call, &self.env.cwd); // The effect is armed only after this exit is accepted for dispatch. Ok(Some(FrameExit::OsCall { function_call: call, @@ -1113,6 +1144,22 @@ impl<'h> VM<'h> { self.finish_host_turn(result) } + /// Runs an export made after [`Self::run_external`] has returned, with the + /// execution clock running, so a user `__repr__` it calls counts towards + /// the time limits. Like `run_external` it must not nest: an export inside + /// the loop (`os.getenv`'s default) is already on the clock and calls + /// `export` directly. + pub(crate) fn export_on_clock(&mut self, export: impl FnOnce(&mut Self) -> RunResult) -> RunResult { + self.heap.tracker.on_execution_start(); + let result = export(self); + self.heap.tracker.on_execution_stop(); + // A container repr truncates on timeout (`...[timeout]`) rather than failing. + result.and_then(|value| match self.heap.tracker.check_time() { + Ok(()) => Ok(value), + Err(err) => Err(err.into()), + }) + } + /// Epilogue for every host-boundary execution window (here, and the /// uncaught branch of `resume_with_exception`, which ends a turn without /// entering the loop): re-checks both resource limits so an @@ -1470,31 +1517,19 @@ impl<'h> VM<'h> { Opcode::UnaryNeg => try_catch!(self, self.unary_neg()), Opcode::UnaryPos => try_catch!(self, self.unary_pos()), Opcode::UnaryInvert => try_catch!(self, self.unary_invert()), - // In-place Operations - route through exception handling. - // `+=`/`-=`/`&=`/`|=` first try a true in-place `Counter` op - // (mutating the left operand); everything else — and the - // non-Counter fallback — reuses the binary implementation, since - // Monty's other types have no distinct in-place form. + // `+=`, `-=`, `*=`, `&=`, `|=`, and `^=` try mutation before binary fallback. Opcode::InplaceAdd => try_catch!(self, self.inplace_add()), Opcode::InplaceSub => try_catch!(self, self.inplace_sub()), - Opcode::InplaceMul => try_catch!(self, self.binary_mult()), + Opcode::InplaceMul => try_catch!(self, self.inplace_mult()), Opcode::InplaceDiv => try_catch!(self, self.binary_div()), Opcode::InplaceFloorDiv => try_catch!(self, self.binary_floordiv()), Opcode::InplaceMod => try_catch!(self, self.binary_mod()), Opcode::InplacePow => try_catch!(self, self.binary_pow()), - Opcode::InplaceAnd => { - try_catch!(self, self.inplace_and()); - } + Opcode::InplaceAnd => try_catch!(self, self.inplace_and()), Opcode::InplaceOr => try_catch!(self, self.inplace_or()), - Opcode::InplaceXor => { - try_catch!(self, self.binary_xor()); - } - Opcode::InplaceLShift => { - try_catch!(self, self.binary_lshift()); - } - Opcode::InplaceRShift => { - try_catch!(self, self.binary_rshift()); - } + Opcode::InplaceXor => try_catch!(self, self.inplace_xor()), + Opcode::InplaceLShift => try_catch!(self, self.binary_lshift()), + Opcode::InplaceRShift => try_catch!(self, self.binary_rshift()), // Collection Building - route through exception handling Opcode::BuildList => { let count = self.current_frame.fetch_u16() as usize; @@ -1884,6 +1919,14 @@ impl<'h> VM<'h> { let error = self.assert_failed_msg(cmp_op); catch!(self, error); } + Opcode::RaiseFrom => { + let cause = self.pop(); + let exc = self.pop(); + if let Some(result) = self.raise_with_cause(exc, cause) { + return Err(result); + } + yield_if_parked!(self); + } Opcode::Reraise => { // Clone rather than pop: a locally caught bare raise must // preserve its enclosing handler's active exception. @@ -1978,7 +2021,9 @@ impl<'h> VM<'h> { let instance = self.pop(); return Ok(FrameExit::Return(instance)); } - // Instance already on the caller's stack — push nothing. + // Instance (or imported module) already on the caller's + // stack — push nothing. + try_catch!(self, self.finish_module_init()); } else if stop { // This frame indicated evaluation should stop - return to host with value // e.g. `evaluate_function` @@ -2059,14 +2104,15 @@ impl<'h> VM<'h> { } } - /// Loads a top-level built-in or suspends with [`OsFunctionCall::Import`]. - /// The host's value becomes the module; `NotFound` raises `ModuleNotFoundError`. + /// Loads a top-level built-in or a cached file module, or suspends with + /// [`OsFunctionCall::Import`]: the host's value becomes the module, and a + /// host with no such module falls back to a `.py` file (see `module_finder`). /// `LoadSubmodule` resolves the remaining dotted components. fn load_module(&mut self, module_id: u16) -> CallResult { let name_id = StringId::from_index(module_id); match self.interns.static_string(name_id).and_then(StandardLib::from_static) { Some(module) => CallResult::Value(Value::Ref(module.create(self))), - None => CallResult::OsCall(OsFunctionCall::Import(self.interns.get_str(name_id).to_owned())), + None => self.import_top_level(self.interns.get_str(name_id)), } } @@ -2185,7 +2231,8 @@ impl<'h> VM<'h> { Some( PendingEffect::Post(PostConversionEffect::DiscardResult | PostConversionEffect::SleepResult { .. }) | PendingEffect::Pre(_) - | PendingEffect::Scan(_), + | PendingEffect::Scan(_) + | PendingEffect::Import(_), ) | None => Ok(Some(value)), }; @@ -2319,6 +2366,7 @@ impl<'h> VM<'h> { }; } PendingEffect::Scan(effect) => effect.release(self.heap), + PendingEffect::Import(_) => {} // Hold no state or heap references — nothing to roll back. PendingEffect::Pre(_) | PendingEffect::Post( @@ -2424,7 +2472,7 @@ impl<'h> VM<'h> { should_return } - /// Releases what a finished frame owns: its stack region and namespace. + /// Releases what a finished frame owns: its stack region, open handlers and namespace. #[inline] fn cleanup_frame_state(&mut self, frame: CallFrame<'_>) { // Clean up frame's stack region (locals + operand stack, which now @@ -2433,6 +2481,11 @@ impl<'h> VM<'h> { self.stack .drain(frame.stack_base()..) .for_each(|value| value.drop_with(&mut *self.heap)); + // An exception unwinding out of a handler leaves that handler's entry + // behind; a later raise in the caller must not see it as being handled. + self.exception_stack + .drain(frame.exception_stack_base()..) + .drop_with(self.heap); // Almost every frame has no namespace; skip the release call for those. if let Some(namespace) = frame.namespace { namespace.drop_with(self.heap); @@ -2906,6 +2959,7 @@ impl Drop for VM<'_> { self.cleanup_current_task(); self.scheduler.cleanup(self.heap); self.globals.drain(..).drop_with(self.heap); + mem::take(&mut self.modules).drop_with(self.heap); self.json_string_cache.drop_all(self.heap); } } diff --git a/crates/bashkit-monty/src/bytecode/vm/module_cache.rs b/crates/bashkit-monty/src/bytecode/vm/module_cache.rs new file mode 100644 index 000000000..f08d97dd9 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/module_cache.rs @@ -0,0 +1,102 @@ +//! The session's modules imported from `.py` files: CPython's `sys.modules`, +//! restricted to file modules. + +use std::collections::BTreeMap; + +use crate::{ + heap::{ContainsHeap, DropWithContext, HeapId}, + value::Value, +}; + +/// Modules imported from files this session, by fully-qualified dotted name. +/// +/// Each file runs once: a later import of the name binds the cached module. A +/// module is cached before its body runs, so a circular import binds it partly +/// initialised, and dropped again if the body raises, so the next import retries. +/// Bundled and host modules are never cached. Every `HeapId` is OWNED. +// TODO: back a live `sys.modules` dict with this, and add `importlib.reload`. +#[derive(Debug, Default, serde::Serialize, serde::Deserialize)] +pub(crate) struct ModuleCache(BTreeMap); + +/// A cached module, and whether its body is still running. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +struct CachedModule { + module: HeapId, + initializing: bool, +} + +impl ModuleCache { + /// Whether no file module is cached: a session that never imported one + /// skips the module checks on every `__init__` return. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// An owned reference to the module cached as `name`. + pub fn get(&self, name: &str, heap: &impl ContainsHeap) -> Option { + self.0.get(name).map(|cached| { + heap.heap().inc_ref(cached.module); + Value::Ref(cached.module) + }) + } + + /// The module cached as `name`, borrowed. + pub fn get_id(&self, name: &str) -> Option { + self.0.get(name).map(|cached| cached.module) + } + + /// Caches the borrowed `module` as `name` before its body runs, taking a reference to it. + pub fn insert(&mut self, name: String, module: HeapId, heap: &mut impl ContainsHeap) { + heap.heap().inc_ref(module); + let cached = CachedModule { + module, + initializing: true, + }; + if let Some(old) = self.0.insert(name, cached) { + heap.heap_mut().dec_ref(old.module); + } + } + + /// Whether `module`, cached as `name`, is still running its body. + pub fn is_initializing(&self, name: &str, module: HeapId) -> bool { + self.0 + .get(name) + .is_some_and(|cached| cached.module == module && cached.initializing) + } + + /// Marks `name` initialised once `module`'s body has returned. + pub fn finish(&mut self, name: &str, module: HeapId) { + if let Some(cached) = self.0.get_mut(name) + && cached.module == module + { + cached.initializing = false; + } + } + + /// Forgets `name` if it still caches `module`, whose body raised. + pub fn remove_failed(&mut self, name: &str, module: HeapId, heap: &mut impl ContainsHeap) { + if self.0.get(name).is_some_and(|cached| cached.module == module) { + self.0.remove(name); + heap.heap_mut().dec_ref(module); + } + } + + /// Forgets every module whose body never finished, when the execution + /// running it is abandoned, so the next import runs the file again. + pub fn remove_unfinished(&mut self, heap: &mut impl ContainsHeap) { + self.0.retain(|_, cached| { + if cached.initializing { + heap.heap_mut().dec_ref(cached.module); + } + !cached.initializing + }); + } +} + +impl DropWithContext for ModuleCache { + fn drop_with(self, ctx: &mut C) { + for cached in self.0.into_values() { + ctx.heap_mut().dec_ref(cached.module); + } + } +} diff --git a/crates/bashkit-monty/src/bytecode/vm/module_finder.rs b/crates/bashkit-monty/src/bytecode/vm/module_finder.rs new file mode 100644 index 000000000..e00591778 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/module_finder.rs @@ -0,0 +1,384 @@ +//! Imports of modules from `.py` files. +//! +//! An import the sandbox neither bundles nor caches is one `import` OS call +//! carrying the module's dotted name and the directories its file may be in: +//! the working directory for a top-level name, the package's `__path__` for a +//! submodule. The host does the whole search, checking its own modules first +//! as CPython checks built-in modules before `sys.path`, and answers with a +//! host module, the [`ModuleFile`] it found, or not-found. A found file is +//! compiled and run here as the module, so each module costs one round trip. + +use std::sync::Arc; + +use monty_types::{ExcType, ExtFunctionResult, ImportArgs, MAX_SEARCH_DIRS, ModuleFile, OsFunctionCall}; + +use super::{ + FrameExit, FrameNamespace, VM, + namespace::{FrameGlobals, MissingNames}, +}; +use crate::{ + builtins::eval_exec::{SnippetSource, compile_and_push}, + bytecode::CallResult, + exception_private::{ExcTypeExt, ExceptionRaise, RunError, RunResult, SimpleException}, + heap::{DropWithContext, HeapData, HeapId, HeapReadOutput}, + intern::StringId, + os_dispatch::PendingEffect, + prepare::SnippetNames, + types::{Dict, List, Module, str::allocate_string}, + value::Value, + virtual_path::posix_join, +}; + +/// Where a top-level import searches, in order: CPython's `sys.path`. +// TODO(site-packages): configured entries (e.g. a read-only site-packages +// mount from `OsPolicy`), exposed read-only as `sys.path`. +#[derive(Clone, Copy)] +enum SearchEntry { + /// The working directory, CPython's `''` entry. + Cwd, +} + +/// The search path of a top-level import. +const SEARCH_PATH: &[SearchEntry] = &[SearchEntry::Cwd]; + +/// What an import raises when the host has no module. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +enum OnMiss { + /// `import name` and `import pkg.sub` raise `ModuleNotFoundError`. + ModuleNotFound, + /// `from pkg import sub` raises `ImportError` naming `pkg`'s file. + CannotImport { + /// The parent package's file, for the message. + origin: String, + /// Whether the parent's body was still running, which the message points out. + partial: bool, + }, +} + +/// An `import` call in flight, armed as its pending effect: a submodule's +/// suspended instruction does not name the module, and a miss's error depends +/// on the statement. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct PendingImport { + /// The fully-qualified dotted module name, e.g. `pkg.sub`. + name: String, + on_miss: OnMiss, +} + +impl PendingImport { + /// A top-level `import name`, which raises `ModuleNotFoundError` on a miss. + pub(crate) fn top_level(name: String) -> Self { + Self { + name, + on_miss: OnMiss::ModuleNotFound, + } + } + + /// Suspends with the `import` call for this module, searching `search_path`. + fn suspend(self, search_path: Vec) -> CallResult { + CallResult::OsCallWithEffect { + call: OsFunctionCall::Import(ImportArgs { + module: self.name.clone(), + search_path, + }), + effect: PendingEffect::Import(self), + } + } +} + +/// A file module an import reaches through, read before the search for one of its submodules. +struct FileParent { + name: String, + origin: String, + /// Whether its body is still running, as in a circular import. + initializing: bool, + /// The package's `__path__`; `None` for a plain module, which has no submodules. + search_path: Option>, +} + +impl VM<'_> { + /// `import name` for a name that is not bundled: the cached file module, + /// else the host's `import` call, searching [`SEARCH_PATH`]. + pub(super) fn import_top_level(&mut self, name: &str) -> CallResult { + if let Some(module) = self.modules.get(name, self.heap) { + CallResult::Value(module) + } else { + let search_path = SEARCH_PATH + .iter() + .map(|entry| match entry { + SearchEntry::Cwd => self.env.cwd.to_string(), + }) + .collect(); + PendingImport::top_level(name.to_owned()).suspend(search_path) + } + } + + /// `import pkg.sub` past a file module: the cached submodule, else the + /// host's `import` call searching the package's `__path__`. `None` when + /// `parent` is not a file module. + pub(super) fn import_file_submodule(&mut self, parent: &Value, path_id: StringId) -> Option> { + let parent = self.file_parent(parent)?; + let name = self.interns.get_str(path_id); + Some(match parent.search_path { + None => Err(ExcType::module_not_found_error(name, Some(&parent.name))), + Some(dirs) => Ok(match self.modules.get(name, self.heap) { + Some(module) => CallResult::Value(module), + None => PendingImport::top_level(name.to_owned()).suspend(dirs), + }), + }) + } + + /// `from pkg import name` where `pkg` has no attribute `name`: for a file + /// package, its submodule `name`. `None` when `parent` is not a file module. + pub(super) fn import_file_attr(&mut self, parent: &Value, name_id: StringId) -> Option> { + let parent = self.file_parent(parent)?; + let attr = self.interns.get_str(name_id); + Some(match parent.search_path { + None => Err(cannot_import(attr, &parent.name, &parent.origin, parent.initializing)), + Some(dirs) => { + let name = format!("{}.{attr}", parent.name); + Ok(if let Some(module) = self.modules.get(&name, self.heap) { + CallResult::Value(module) + } else { + let on_miss = OnMiss::CannotImport { + origin: parent.origin, + partial: parent.initializing, + }; + PendingImport { name, on_miss }.suspend(dirs) + }) + } + }) + } + + /// Takes the armed `import` call, if the paused OS call is one. + pub(crate) fn take_pending_import(&mut self) -> Option { + match self.pending_effect.take() { + Some(PendingEffect::Import(pending)) => Some(pending), + other => { + self.pending_effect = other; + None + } + } + } + + /// Resumes an `import` call with the host's answer: a host module value, + /// the module's file to run, an exception raised without carets, or + /// not-found. Futures are rejected because imports cannot await. + pub(crate) fn resume_import( + &mut self, + pending: PendingImport, + result: ExtFunctionResult, + eager_call_id: Option, + ) -> Result { + match (result, eager_call_id) { + (ExtFunctionResult::Return(obj), None) => self.resume(obj), + (ExtFunctionResult::ModuleFile(file), None) => self.resume_import_file(pending.name, file), + (ExtFunctionResult::Error(exc), None) => { + let mut raise = ExceptionRaise::from(exc); + raise.hide_caret = true; + self.resume_with_exception(RunError::Exc(raise)) + } + (ExtFunctionResult::NotFound(_), None) => { + self.resume_with_exception(missed_import(&pending.name, pending.on_miss)) + } + (ExtFunctionResult::Future(_), _) | (_, Some(_)) => { + let message = format!("import of '{}' cannot be answered with a future", pending.name); + self.resume_with_exception(SimpleException::new_msg(ExcType::RuntimeError, message).into()) + } + } + } + + /// Runs the file the host found as the module `name`. + fn resume_import_file(&mut self, name: String, file: ModuleFile) -> Result { + let source = Arc::from(file.source); + // Compiling is execution: it counts against the time limits. + self.heap.tracker.on_execution_start(); + let result = self.run_file_module(name, &file.path, &source); + self.heap.tracker.on_execution_stop(); + match result { + Ok(()) => self.run_external(), + Err(err) => self.resume_with_exception(err), + } + } + + /// After a module body returns: marks it initialised and binds a submodule + /// on its parent package, as CPython does once the import succeeds. A no-op + /// for an `__init__` frame. + pub(super) fn finish_module_init(&mut self) -> RunResult<()> { + let Some((module, name)) = self.file_module_on_stack() else { + return Ok(()); + }; + self.modules.finish(&name, module); + let Some((parent_name, leaf)) = name.rsplit_once('.') else { + return Ok(()); + }; + let namespace = match self.modules.get_id(parent_name).map(|parent| self.heap.get(parent)) { + Some(HeapData::Module(parent)) => parent.namespace(), + _ => None, + }; + let Some(namespace) = namespace else { + return Ok(()); + }; + let key = allocate_string(leaf, self.heap); + self.heap.inc_ref(module); + let HeapReadOutput::Dict(dict) = self.heap.read(namespace) else { + unreachable!("a file module's namespace is a dict") + }; + let old = dict.set(key, Value::Ref(module), self)?; + old.drop_with(self); + Ok(()) + } + + /// After a module fails to load (its body raised or did not compile): + /// forgets the file module on top of the stack, so the next import retries + /// the file. Returns whether one was there. + pub(super) fn forget_failed_module(&mut self) -> bool { + match self.file_module_on_stack() { + Some((module, name)) => { + self.modules.remove_failed(&name, module, self.heap); + true + } + None => false, + } + } + + /// Runs `source`, read from `path`, as the module `name`: caches the module, + /// pushes it as the import's result, then pushes its body's frame, which + /// leaves it there on return (see `CallFrame::is_initializer`). + fn run_file_module(&mut self, name: String, path: &str, source: &Arc) -> RunResult<()> { + let namespace = self.module_namespace(&name, path); + let module = Module::file(name.clone(), namespace, path.to_owned()); + let module_id = self.heap.allocate(HeapData::Module(Box::new(module))); + self.modules.insert(name, module_id, self.heap); + self.push(Value::Ref(module_id)); + + self.heap.inc_ref(namespace); + let frame_namespace = Box::new(FrameNamespace::Snippet { + globals: FrameGlobals::Dict(namespace), + locals: None, + globals_first: false, + missing: MissingNames::Raise, + }); + // TODO(site-packages): reuse compiled code across sessions; a large + // package otherwise recompiles every module in every session. + let kind = SnippetSource::File { path }; + match compile_and_push(kind, source, SnippetNames::NameOverDict, frame_namespace, self) { + Ok(_) => { + self.current_frame_mut().is_initializer = true; + Ok(()) + } + Err(err) => { + self.forget_failed_module(); + self.pop().drop_with(self); + Err(err) + } + } + } + + /// A new module's globals: `__name__`, `__file__`, `__package__`, and + /// `__path__` for a package, which a `path` ending in `/__init__.py` is. + /// Returns an owned reference. + fn module_namespace(&mut self, name: &str, path: &str) -> HeapId { + let package_dir = path.strip_suffix("/__init__.py"); + let package = match (package_dir, name.rsplit_once('.')) { + (Some(_), _) => name, + (None, Some((parent, _))) => parent, + (None, None) => "", + }; + let mut entries = vec![ + ("__name__", allocate_string(name, self.heap)), + ("__file__", allocate_string(path, self.heap)), + ("__package__", allocate_string(package, self.heap)), + ]; + if let Some(dir) = package_dir { + let dir = allocate_string(dir, self.heap); + entries.push(( + "__path__", + Value::Ref(self.heap.allocate(HeapData::List(List::new(vec![dir])))), + )); + } + let mut dict = Dict::new(); + for (key, value) in entries { + let key = allocate_string(key, self.heap); + // Few string keys into an empty dict: hashing cannot fail and growth is negligible. + dict.set_without_growth_check(key, value, self) + .expect("module dunder keys are strings, so hashing cannot fail"); + } + self.heap.allocate(HeapData::Dict(dict)) + } + + /// `value` as a file module, with what an import of one of its submodules needs. + fn file_parent(&self, value: &Value) -> Option { + let id = value.ref_id()?; + let HeapData::Module(module) = self.heap.get(id) else { + return None; + }; + let namespace = module.namespace()?; + let HeapData::Dict(dict) = self.heap.get(namespace) else { + return None; + }; + let search_path = dict + .get_by_str("__path__", self.heap, self.interns) + .map(|path| self.search_path(path)); + let name = module.name_str(self.interns); + Some(FileParent { + initializing: self.modules.is_initializing(name, id), + name: name.to_owned(), + origin: module.origin().unwrap_or_default().to_owned(), + search_path, + }) + } + + /// A package's `__path__` (a list or tuple) as directories joined to the + /// working directory, skipping anything that is not a `str` or that holds + /// a NUL byte (the host skips those too), up to the [`MAX_SEARCH_DIRS`] it searches. + fn search_path(&self, path: &Value) -> Vec { + let dirs = match path.ref_id().map(|id| self.heap.get(id)) { + Some(HeapData::List(list)) => list.as_slice(), + Some(HeapData::Tuple(tuple)) => tuple.as_slice(), + _ => return Vec::new(), + }; + dirs.iter() + .filter_map(|dir| dir.as_str_heap(self.heap, self.interns)) + .filter(|dir| !dir.contains('\0')) + .take(MAX_SEARCH_DIRS) + .map(|dir| posix_join(&self.env.cwd, dir)) + .collect() + } + + /// The file module on top of the operand stack, where an import pushes it + /// before running its body, with its dotted name. Checked on every + /// `__init__` return too, so an empty cache answers before touching the heap. + fn file_module_on_stack(&self) -> Option<(HeapId, String)> { + if self.modules.is_empty() { + return None; + } + let id = self.stack.last()?.ref_id()?; + match self.heap.get(id) { + HeapData::Module(module) if module.namespace().is_some() => { + Some((id, module.name_str(self.interns).to_owned())) + } + _ => None, + } + } +} + +/// The error for an import the host has no module for. +fn missed_import(name: &str, on_miss: OnMiss) -> RunError { + match on_miss { + OnMiss::ModuleNotFound => ExcType::module_not_found_error(name, None), + OnMiss::CannotImport { origin, partial } => { + let (parent, attr) = name.rsplit_once('.').expect("a submodule name is dotted"); + cannot_import(attr, parent, &origin, partial) + } + } +} + +/// `from parent import attr` failing, noting a parent whose body is still running. +fn cannot_import(attr: &str, parent: &str, origin: &str, partial: bool) -> RunError { + if partial { + ExcType::cannot_import_name_partial(attr, parent, origin) + } else { + ExcType::cannot_import_name(attr, parent, Some(origin)) + } +} diff --git a/crates/bashkit-monty/src/bytecode/vm/namespace.rs b/crates/bashkit-monty/src/bytecode/vm/namespace.rs index 8fd6ab68f..5a9187f0e 100644 --- a/crates/bashkit-monty/src/bytecode/vm/namespace.rs +++ b/crates/bashkit-monty/src/bytecode/vm/namespace.rs @@ -7,7 +7,7 @@ //! globals through that dict at every call. [`FrameNamespace`] records which //! case a frame is in; the descriptor owns the dict references it names. -use std::iter; +use std::{iter, ops::Not}; use ahash::AHashSet; @@ -18,7 +18,7 @@ use crate::{ heap::{ContainsHeap, DropGuard, DropWithContext, HeapData, HeapId, HeapReadOutput}, intern::{CompileInterns, FunctionId, StringId}, prepare::SnippetNames, - types::Dict, + types::{Dict, ForwardRef}, value::Value, }; @@ -54,7 +54,57 @@ pub(crate) enum FrameNamespace { globals: FrameGlobals, /// The snippet's locals dict, if it runs with one distinct from its globals. locals: Option, + /// Bound slot globals shadow `locals`: the lookup order CPython's + /// `get_type_hints` gives a class forward reference (module, then class). + #[serde(default, skip_serializing_if = "Not::not")] + globals_first: bool, + /// What a name nothing resolves loads as. + #[serde(default)] + missing: MissingNames, }, + /// A frame running an `__annotate__` function (PEP 649): names resolve by + /// name through `classdict`, a copy of the class namespace for a class's + /// annotations, then `globals` — CPython's `LOAD_FROM_DICT_OR_GLOBALS` — + /// with `missing` supplying CPython's "fake globals" for `FORWARDREF` and `STRING`. + Annotate { + /// Where the function's globals live. + globals: FrameGlobals, + /// The class namespace consulted first, for a class's `__annotate__`. + classdict: Option, + /// What a name nothing resolves loads as. + missing: MissingNames, + }, +} + +/// What a snippet does with a name nothing resolves. +#[derive(Debug, Default, serde::Serialize, serde::Deserialize)] +pub(crate) enum MissingNames { + /// Ask the host for a slot global, then raise `NameError`. + #[default] + Raise, + /// Load a `ForwardRef` stringifier instead: an annotation evaluating in + /// `annotationlib.Format.FORWARDREF`, where every operation on the result + /// composes source text (see `types/forward_ref.rs`). + ForwardRef { + /// The function or class the annotation belongs to, or `None`; OWNED. + owner: Value, + /// Whether the annotation was written in a class body. + is_class: bool, + /// Stringify every name, bound or not: annotationlib's retry after an + /// annotation raised, which runs it against empty globals. + every_name: bool, + }, + /// Raise `NameError` without asking the host: the plain evaluation + /// `annotationlib`'s `FORWARDREF` tries first, which must never suspend. + NameError, +} + +impl DropWithContext for MissingNames { + fn drop_with(self, ctx: &mut C) { + if let Self::ForwardRef { owner, .. } = self { + owner.drop_with(ctx); + } + } } impl FrameNamespace { @@ -65,11 +115,19 @@ impl FrameNamespace { Self::Snippet { globals: FrameGlobals::Slots, .. + } + | Self::Annotate { + globals: FrameGlobals::Slots, + .. } => None, Self::Function { globals } | Self::Snippet { globals: FrameGlobals::Dict(globals), .. + } + | Self::Annotate { + globals: FrameGlobals::Dict(globals), + .. } => Some(*globals), } } @@ -89,13 +147,24 @@ impl DropWithContext for Box { fn drop_with(self, ctx: &mut C) { match *self { FrameNamespace::Function { globals } => ctx.heap_mut().dec_ref(globals), - FrameNamespace::Snippet { globals, locals } => { + FrameNamespace::Snippet { + globals, + locals, + missing, + .. + } + | FrameNamespace::Annotate { + globals, + classdict: locals, + missing, + } => { if let FrameGlobals::Dict(globals) = globals { ctx.heap_mut().dec_ref(globals); } if let Some(locals) = locals { ctx.heap_mut().dec_ref(locals); } + missing.drop_with(ctx); } } } @@ -122,6 +191,7 @@ impl<'h> VM<'h> { Some(FrameNamespace::Snippet { globals, locals: frame_locals, + .. }) => { let (globals, frame_locals) = (*globals, *frame_locals); if let FrameGlobals::Dict(dict) = globals { @@ -146,6 +216,18 @@ impl<'h> VM<'h> { self.heap.inc_ref(dict); (FrameGlobals::Dict(dict), locals) } + // An annotation's `eval()` sees the annotate function's globals and locals. + Some(FrameNamespace::Annotate { globals, .. }) => { + let globals = *globals; + let locals = match locals { + Some(dict) => Some(dict), + None => Some(self.snapshot_locals()?), + }; + if let FrameGlobals::Dict(dict) = globals { + self.heap.inc_ref(dict); + } + (globals, locals) + } None => { let locals = match (locals, self.namespace_frame().function_id) { (Some(dict), _) => Some(dict), @@ -161,15 +243,24 @@ impl<'h> VM<'h> { (FrameGlobals::Slots, Some(_)) => SnippetNames::NameOverSlots, (FrameGlobals::Slots, None) => SnippetNames::Slots, }; - Ok((names, Box::new(FrameNamespace::Snippet { globals, locals }))) + Ok(( + names, + Box::new(FrameNamespace::Snippet { + globals, + locals, + globals_first: false, + missing: MissingNames::Raise, + }), + )) } /// Admits a snippet before publishing its compilation and installing its frame. /// A recursion-limit rejection discards both the overlay and the owned namespace. + /// `overlay` is `None` when `func_id` is already committed (a cached hint snippet). pub(crate) fn push_snippet_frame( &mut self, func_id: FunctionId, - overlay: CompileInterns<'_>, + overlay: Option>, namespace: Box, ) -> RunResult<()> { let mut namespace_guard = DropGuard::new(namespace, self); @@ -178,7 +269,9 @@ impl<'h> VM<'h> { vm.incr_recursion()?; // Publication makes the code borrowable for the run. Nothing fallible or // re-entrant may intervene between admission and installing the frame. - overlay.commit(); + if let Some(overlay) = overlay { + overlay.commit(); + } let (namespace, vm) = namespace_guard.into_parts(); let code = &vm.interns.get_function(func_id).code; let frame = CallFrame::new_function( @@ -206,6 +299,7 @@ impl<'h> VM<'h> { | FrameNamespace::Snippet { globals: FrameGlobals::Dict(dict), locals: None, + .. }, ) => { let dict = *dict; @@ -215,8 +309,9 @@ impl<'h> VM<'h> { Some(FrameNamespace::Snippet { globals: FrameGlobals::Slots, locals: None, + .. }) => self.snapshot_globals()?, - Some(FrameNamespace::Function { .. }) => self.snapshot_locals()?, + Some(FrameNamespace::Function { .. } | FrameNamespace::Annotate { .. }) => self.snapshot_locals()?, None if self.namespace_frame().function_id.is_none() => self.snapshot_globals()?, None => self.snapshot_locals()?, }; @@ -249,24 +344,54 @@ impl<'h> VM<'h> { /// resolves nothing else for `exec(src, {})`. pub(super) fn load_name(&mut self, slot: u16, name_id: StringId, flags: u8) -> RunResult> { let (globals, locals) = self.frame_namespace(); + let stringify = self.frame_stringifies_names(); + let without_host = self.frame_names_without_host(); + if stringify == Some(true) { + let stringifier = self.stringifier(name_id); + self.push(stringifier); + return Ok(None); + } if flags & NAME_GLOBAL_ONLY == 0 && let Some(locals) = locals - && let Some(value) = self.namespace_get(locals, name_id)? { - self.push(value); - return Ok(None); + if globals == FrameGlobals::Slots + && self.frame_globals_first() + && !matches!(self.globals[usize::from(slot)], Value::Undefined) + { + let value = self.globals[usize::from(slot)].clone_with_heap(self.heap); + self.push(value); + return Ok(None); + } + if let Some(value) = self.namespace_get(locals, name_id)? { + self.push(value); + return Ok(None); + } } match globals { - FrameGlobals::Slots if flags & NAME_CALLABLE != 0 => { + FrameGlobals::Slots if flags & NAME_CALLABLE != 0 && stringify.is_none() && !without_host => { self.load_global_callable(slot, name_id); Ok(None) } - FrameGlobals::Slots => self.load_global(slot), + // An unresolved name stringifies, or raises, rather than asking the host. + FrameGlobals::Slots => match self.load_global(slot)? { + Some(FrameExit::NameLookup { .. }) if stringify.is_some() => { + let stringifier = self.stringifier(name_id); + self.push(stringifier); + Ok(None) + } + Some(FrameExit::NameLookup { .. }) if without_host => { + Err(ExcType::name_error(self.interns.get_str(name_id)).into()) + } + exit => Ok(exit), + }, FrameGlobals::Dict(dict) => { if let Some(value) = self.namespace_get(dict, name_id)? { self.push(value); } else if let Some(builtin) = self.builtin_for_name(name_id) { self.push(builtin); + } else if stringify.is_some() { + let stringifier = self.stringifier(name_id); + self.push(stringifier); } else { return Err(ExcType::name_error(self.interns.get_str(name_id)).into()); } @@ -275,6 +400,98 @@ impl<'h> VM<'h> { } } + /// Whether the running code was compiled under `from __future__ import + /// annotations`, which an `eval()` / `exec()` it calls inherits. + pub(crate) fn frame_future_annotations(&self) -> bool { + self.current_frame.code.future_annotations() + } + + /// Whether the current frame stringifies unresolved names, and if so whether + /// it stringifies every name (see [`MissingNames::ForwardRef`]). + fn frame_stringifies_names(&self) -> Option { + match self.current_frame.namespace.as_deref() { + Some( + FrameNamespace::Snippet { + missing: MissingNames::ForwardRef { every_name, .. }, + .. + } + | FrameNamespace::Annotate { + missing: MissingNames::ForwardRef { every_name, .. }, + .. + }, + ) => Some(*every_name), + _ => None, + } + } + + /// Whether the current frame raises `NameError` for a name the host would + /// otherwise be asked for (see [`MissingNames::NameError`]). + fn frame_names_without_host(&self) -> bool { + matches!( + self.current_frame.namespace.as_deref(), + Some( + FrameNamespace::Snippet { + missing: MissingNames::NameError, + .. + } | FrameNamespace::Annotate { + missing: MissingNames::NameError, + .. + } + ) + ) + } + + /// A new `ForwardRef` stringifier for `name_id`, owned by the current frame's annotation owner. + fn stringifier(&mut self, name_id: StringId) -> Value { + let Some( + FrameNamespace::Snippet { + globals, + missing: MissingNames::ForwardRef { owner, is_class, .. }, + .. + } + | FrameNamespace::Annotate { + globals, + missing: MissingNames::ForwardRef { owner, is_class, .. }, + .. + }, + ) = self.current_frame.namespace.as_deref() + else { + unreachable!("stringifier requested outside a FORWARDREF evaluation") + }; + if let FrameGlobals::Dict(dict) = globals { + self.heap.inc_ref(*dict); + } + let forward_ref = ForwardRef::stringifier( + Value::InternString(name_id), + owner.clone_with_heap(self.heap), + *is_class, + *globals, + ); + Value::Ref(self.heap.allocate(HeapData::ForwardRef(Box::new(forward_ref)))) + } + + /// Whether a `FORWARDREF` annotation evaluation is on the stack, during + /// which every stringifier composes source text (see `types/forward_ref.rs`). + pub(crate) fn in_forward_ref_evaluation(&self) -> bool { + self.suspended_frames + .iter() + .chain(iter::once(&self.current_frame)) + .any(|frame| { + matches!( + frame.namespace.as_deref(), + Some( + FrameNamespace::Snippet { + missing: MissingNames::ForwardRef { .. }, + .. + } | FrameNamespace::Annotate { + missing: MissingNames::ForwardRef { .. }, + .. + } + ) + ) + }) + } + /// `StoreName`: pops the value and binds `name_id` in the locals dict when /// there is one (and `NAME_GLOBAL_ONLY` is clear), else in the globals. pub(super) fn store_name(&mut self, slot: u16, name_id: StringId, flags: u8) -> RunResult<()> { @@ -384,10 +601,22 @@ impl<'h> VM<'h> { match self.current_frame.namespace.as_deref() { None => (FrameGlobals::Slots, None), Some(FrameNamespace::Function { globals }) => (FrameGlobals::Dict(*globals), None), - Some(FrameNamespace::Snippet { globals, locals }) => (*globals, *locals), + Some(FrameNamespace::Snippet { globals, locals, .. }) => (*globals, *locals), + Some(FrameNamespace::Annotate { globals, classdict, .. }) => (*globals, *classdict), } } + /// Whether the current frame is a snippet whose bound slot globals shadow its locals. + fn frame_globals_first(&self) -> bool { + matches!( + self.current_frame.namespace.as_deref(), + Some(FrameNamespace::Snippet { + globals_first: true, + .. + }) + ) + } + /// Looks `name_id` up in a namespace dict, returning an owned value. fn namespace_get(&mut self, dict_id: HeapId, name_id: StringId) -> RunResult> { let HeapReadOutput::Dict(dict) = self.heap.read(dict_id) else { diff --git a/crates/bashkit-monty/src/bytecode/vm/pattern.rs b/crates/bashkit-monty/src/bytecode/vm/pattern.rs index 0e4c025a4..bd922c4a3 100644 --- a/crates/bashkit-monty/src/bytecode/vm/pattern.rs +++ b/crates/bashkit-monty/src/bytecode/vm/pattern.rs @@ -15,10 +15,8 @@ use crate::{ bytecode::op::{MATCH_SHAPE_MAPPING, MATCH_SHAPE_MIN_LEN}, defer_drop, exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, - heap::{DropGuard, DropWithContext, Heap, HeapData, HeapReadOutput}, - types::{ - Dict, PyTrait, Type, instance::class_name, set::set_element_hash, str::allocate_string, tuple::allocate_tuple, - }, + heap::{DropGuard, DropWithContext, HeapData, HeapReadOutput}, + types::{Dict, PyTrait, Type, instance::class_name, set::set_element_hash, tuple::allocate_tuple}, value::{EitherStr, Value}, }; @@ -309,7 +307,7 @@ fn class_pattern_names( match class_match_args(cls, nargs, vm)? { MatchArgs::SelfMatch => names.push(Value::None), MatchArgs::Names(positional) => { - names.extend(positional.iter().map(|name| either_str_value(name, vm.heap))); + names.extend(positional.iter().map(|name| name.as_value(vm.heap))); } } } @@ -355,7 +353,7 @@ fn class_match_args(cls: &Value, nargs: usize, vm: &mut VM<'_>) -> RunResult { + Value::Builtin(Builtins::Type(t)) if SELF_MATCHING_TYPES.contains(&(*t).into()) => { check_count(1, vm).map(|()| MatchArgs::SelfMatch) } _ => check_count(0, vm).map(|()| MatchArgs::Names(Vec::new())), @@ -405,14 +403,6 @@ fn class_match_args(cls: &Value, nargs: usize, vm: &mut VM<'_>) -> RunResult Value { - match name { - EitherStr::Interned(id) => Value::InternString(*id), - EitherStr::Heap(text) => allocate_string(text.clone(), heap), - } -} - /// `TypeError: Foo.__match_args__ must be a tuple (got list)`. fn match_args_type_error(cls: &Value, match_args: &Value, vm: &VM<'_>) -> RunError { let class = class_pattern_name(cls, vm); @@ -432,7 +422,7 @@ fn positional_count_error(cls: &Value, allowed: usize, given: usize, vm: &VM<'_> /// The class's `__name__`, as CPython's class pattern errors spell it. fn class_pattern_name(cls: &Value, vm: &VM<'_>) -> String { match cls { - Value::Builtin(Builtins::Type(t)) => t.dunder_name(vm.heap, vm.interns).into_owned(), + Value::Builtin(Builtins::Type(t)) => Type::from(*t).dunder_name(vm.heap, vm.interns).into_owned(), Value::Builtin(Builtins::ExcType(exc_type)) => { let qualified = exc_type.to_string(); qualified.rsplit('.').next().unwrap_or(&qualified).to_owned() diff --git a/crates/bashkit-monty/src/bytecode/vm/scheduler.rs b/crates/bashkit-monty/src/bytecode/vm/scheduler.rs index 873d7b4b0..618f25485 100644 --- a/crates/bashkit-monty/src/bytecode/vm/scheduler.rs +++ b/crates/bashkit-monty/src/bytecode/vm/scheduler.rs @@ -97,7 +97,7 @@ pub(crate) struct SerializedTaskFrame { /// Caller's bytecode offset at the call site (for tracebacks). See /// `CallFrame.call_offset`. pub call_offset: Option, - /// Whether this frame is a class `__init__` (see `CallFrame.is_initializer`). + /// Whether this frame is a class `__init__` or an imported module body (see `CallFrame.is_initializer`). pub is_initializer: bool, /// Frame namespace, owning its dict references (see `CallFrame.namespace`). pub namespace: Option>, diff --git a/crates/bashkit-monty/src/dump_format.rs b/crates/bashkit-monty/src/dump_format.rs index 64a5f7630..37310785c 100644 --- a/crates/bashkit-monty/src/dump_format.rs +++ b/crates/bashkit-monty/src/dump_format.rs @@ -7,6 +7,11 @@ //! and [`Dump::load`]; whether the session was idle or suspended is the //! [`Session`] discriminant, not a separate tag. //! +//! Inline builtin types serialize through `Type`, preserving the names and payloads +//! written before `BuiltinType` was split out. Its own enum order is not the wire +//! order: postcard encoding for builtin `id()` retains `Type::Instance`'s slot. +//! See `builtin_type_tests` in `types/builtin_type.rs` and the legacy serialization fixture. +//! //! # Naming contract //! //! The payload is self-describing: structs are maps keyed by field name and @@ -56,7 +61,7 @@ const MAGIC: &[u8; 6] = b"MONTY\0"; /// /// Before bumping, check there's already been a bump since the last release - multiple bumps /// between releases is unnecessary and can lead to confusion. -pub const DUMP_VERSION: u16 = 14; +pub const DUMP_VERSION: u16 = 15; /// The oldest dump version this build loads. `Dump::load` runs `dump_upgrade` /// over an older dump, rebuilding what the newer versions changed. @@ -208,7 +213,7 @@ pub enum Session { impl Session { /// The session heap and its interns, or `None` for a one-shot run that has completed. - fn heap_and_interns(&mut self) -> Option<(&mut Heap, &Interns)> { + fn heap_and_interns(&mut self) -> Option<(&mut Heap, &mut Interns)> { match self { Self::Idle(repl) => Some(repl.heap_and_interns()), Self::Suspended(progress) => Some(progress.heap_and_interns()), @@ -367,7 +372,7 @@ mod tests { fn serialized_components_match_dump_version() { assert_eq!( opcode_fingerprint(), - 0xa78a_9e6c_3fab_abed, + 0x47f4_8e5e_55da_518f, "opcodes changed for dump version {DUMP_VERSION}, actual: {}", grouped_hex(opcode_fingerprint()) ); @@ -393,7 +398,7 @@ mod tests { ); assert_eq!( variant_name_fingerprint(&type_names), - 0x578d_38b1_7715_f9a1, + 0x4db8_c44f_dbcb_fb2a, "Type variants changed for dump version {DUMP_VERSION}, actual: {}", grouped_hex(variant_name_fingerprint(&type_names)) ); diff --git a/crates/bashkit-monty/src/dump_upgrade.rs b/crates/bashkit-monty/src/dump_upgrade.rs index c1f83431e..77fa0415f 100644 --- a/crates/bashkit-monty/src/dump_upgrade.rs +++ b/crates/bashkit-monty/src/dump_upgrade.rs @@ -14,11 +14,68 @@ //! - It is tested against a fixture the *older* build wrote, which must never be //! regenerated (see `tests/dump_compat.rs`). -use crate::{heap::Heap, intern::Interns, modules::dataclasses}; +use ahash::AHashMap; +use ruff_python_parser::parse_module; + +use crate::{ + heap::Heap, + intern::{Interns, StringId}, + modules::dataclasses, + parse::CodeRange, +}; + +/// The last dump version whose `eval()` positions count from after the source's +/// leading whitespace, which those builds stripped with `str::trim_start`. +const LEGACY_EVAL_OFFSETS_VERSION: u16 = 14; /// Runs every upgrade a dump written at `version` needs over its decoded heap. -pub(crate) fn upgrade(version: u16, heap: &mut Heap, interns: &Interns) { +pub(crate) fn upgrade(version: u16, heap: &mut Heap, interns: &mut Interns) { if version <= dataclasses::LEGACY_DUMP_VERSION { dataclasses::upgrade_legacy_classes(heap, interns); } + if version <= LEGACY_EVAL_OFFSETS_VERSION { + rebase_legacy_eval_offsets(interns); + } +} + +/// Shifts every position in `eval()` code past the leading whitespace the old +/// build stripped, so it indexes the whole source as current positions do. +/// +/// `exec()` shares the snippet source table but never stripped anything. An +/// eval source is recognised by failing to parse as a module, which indenting +/// the expression's line or a non-ASCII space before it causes. A source valid +/// as both (only blank or comment-only lines before unindented code) cannot be +/// told apart and is left as it was, so its positions can still point early. +fn rebase_legacy_eval_offsets(interns: &mut Interns) { + let shifts: AHashMap = interns + .eval_sources() + .filter_map(|(id, source)| { + let shift = u32::try_from(source.len() - source.trim_start().len()).ok()?; + let len = u32::try_from(source.len()).ok()?; + (shift > 0 && parse_module(source).is_err()).then_some((id, (shift, len))) + }) + .collect(); + if shifts.is_empty() { + return; + } + interns.for_each_function_mut(|function| { + let name = &mut function.name.position; + // The snippet's own module function spans the whole source and was never relative. + if let Some(&(shift, len)) = shifts.get(&name.filename) + && !(name.start_byte == 0 && name.end_byte == len) + { + shift_range(name, shift); + } + function.code.for_each_position_mut(|range| { + if let Some(&(shift, _)) = shifts.get(&range.filename) { + shift_range(range, shift); + } + }); + }); +} + +/// Moves `range` `shift` bytes later in its source. +fn shift_range(range: &mut CodeRange, shift: u32) { + range.start_byte = range.start_byte.saturating_add(shift); + range.end_byte = range.end_byte.saturating_add(shift); } diff --git a/crates/bashkit-monty/src/exception_private.rs b/crates/bashkit-monty/src/exception_private.rs index 5cae69b87..ad139bc49 100644 --- a/crates/bashkit-monty/src/exception_private.rs +++ b/crates/bashkit-monty/src/exception_private.rs @@ -1,6 +1,7 @@ use std::{ borrow::Cow, fmt::{self, Display, Write}, + mem, }; use monty_types::{ExcData, JsonErrorData, MontyException, StackFrame, UnicodeErrorData}; @@ -11,7 +12,7 @@ use crate::{ bytecode::{CallResult, VM}, defer_drop, fstring::{FormatError, ascii_escape}, - heap::{DropWithContext, HeapData, HeapRead}, + heap::{DropWithContext, HeapData, HeapId, HeapRead}, intern::{Interns, StaticStrings, StringId}, parse::CodeRange, py_value::PyValue, @@ -175,6 +176,31 @@ pub(crate) trait ExcTypeExt: Sized { Self::type_error("isinstance() argument 2 cannot be a parameterized generic") } + /// Creates the TypeError `typing.get_type_hints()` raises for an object that + /// is neither annotated nor callable: `5 does not have annotations`. + fn no_annotations(obj: &Value, vm: &mut VM<'_>) -> RunError { + match obj.py_repr(vm) { + Ok(repr_value) => { + defer_drop!(repr_value, vm); + let repr = repr_value + .as_str(vm) + .map_or_else(|| format!("<{}>", obj.py_type_name(vm)), str::to_owned); + Self::type_error(format!("{repr} does not have annotations")) + } + Err(err) => err, + } + } + + /// Creates the SyntaxError `typing.get_type_hints()` raises for a forward + /// reference that does not compile as an expression, e.g. `' int'` or `'x = 1'`. + fn forward_ref_not_expression(source: &str) -> RunError { + SimpleException::new_msg( + ExcType::SyntaxError, + format!("Forward reference must be an expression -- got {}", StringRepr(source)), + ) + .into() + } + /// Creates the TypeError for an ordering comparison (`<`, `<=`, `>`, `>=`) /// between values whose types define no ordering, e.g. `1 < 'a'` or two /// instances of a user class without comparison dunders. @@ -261,20 +287,23 @@ pub(crate) trait ExcTypeExt: Sized { /// If the key's string conversion fails (e.g. huge LongInt exceeding /// `INT_MAX_STR_DIGITS`), falls back to the type name so that a /// `KeyError` is always raised rather than a spurious `ValueError`. + /// An uncatchable error (a resource limit hit inside a user `__str__`) is + /// returned as is, so it cannot become a catchable `KeyError`. fn key_error(key: &Value, vm: &mut VM<'_>) -> RunError { - let key_str = match key.py_str(vm) { + match key.py_str(vm) { Ok(key_value) => { // `key_value` is a heap `str` `Value`; extract its text and drop it. defer_drop!(key_value, vm); - if let Ok(s) = key_value.to_str(vm) { + let key_str = if let Some(s) = key_value.as_str(vm) { s.to_owned() } else { format!("<{}>", key.py_type_name(vm)) - } + }; + SimpleException::new_msg(ExcType::KeyError, key_str).into() } - Err(_) => format!("<{}>", key.py_type_name(vm)), - }; - SimpleException::new_msg(ExcType::KeyError, key_str).into() + Err(err @ RunError::UncatchableExc(_)) => err, + Err(_) => SimpleException::new_msg(ExcType::KeyError, format!("<{}>", key.py_type_name(vm))).into(), + } } /// Creates a KeyError for popping from an empty set. @@ -782,7 +811,7 @@ pub(crate) trait ExcTypeExt: Sized { } /// Creates `FileNotFoundError: [Errno 2] No such file or directory: '{path}'`, - /// as raised by `os.chdir('')` without consulting the host. + /// as raised for an empty path without consulting the host. #[must_use] fn file_not_found_error(path: &str) -> RunError { SimpleException::new_msg( @@ -792,6 +821,21 @@ pub(crate) trait ExcTypeExt: Sized { .into() } + /// Creates `FileNotFoundError: [Errno 2] No such file or directory: '{src}' -> '{dst}'`, + /// CPython's two-path form for `os.rename` / `os.replace` with an empty path. + #[must_use] + fn file_not_found_error_pair(src: &str, dst: &str) -> RunError { + SimpleException::new_msg( + ExcType::FileNotFoundError, + format!( + "[Errno 2] No such file or directory: {} -> {}", + StringRepr(src), + StringRepr(dst) + ), + ) + .into() + } + /// Creates `NotADirectoryError: [Errno 20] Not a directory: '{path}'`, as /// raised by `os.chdir` when the host's stat result is not a directory. #[must_use] @@ -821,6 +865,12 @@ pub(crate) trait ExcTypeExt: Sized { Self::type_error("Can't mix strings and bytes in path components") } + /// `object of type '{type}' has no len()` + #[must_use] + fn type_error_no_len(type_name: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("object of type '{type_name}' has no len()")).into() + } + /// Creates the `os.fspath` TypeError, also raised by pure-Python `os` /// functions that call `fspath` internally (e.g. `os.makedirs`): /// `expected str, bytes or os.PathLike object, not {type}`. @@ -1045,7 +1095,7 @@ pub(crate) trait ExcTypeExt: Sized { Ok(repr_value) => { defer_drop!(repr_value, vm); repr_value - .to_str(vm) + .try_to_str(vm) .map_or_else(|_| format!("<{}>", key.py_type_name(vm)), str::to_owned) } Err(err) => return err, @@ -1080,14 +1130,21 @@ pub(crate) trait ExcTypeExt: Sized { SimpleException::new_msg(ExcType::OverflowError, "timestamp out of range for C PyTime_t").into() } - /// The `OverflowError` the `time` conversion functions raise for epoch - /// seconds outside the range a broken-down time can hold: + /// The `OverflowError` the `time` conversion functions and `fromtimestamp()` + /// raise for epoch seconds outside the range a broken-down time can hold: /// `timestamp out of range for platform time_t`. #[must_use] fn timestamp_out_of_range() -> RunError { SimpleException::new_msg(ExcType::OverflowError, "timestamp out of range for platform time_t").into() } + /// The `ValueError` CPython's time conversions raise for a NaN length or + /// timestamp: `Invalid value NaN (not a number)`. + #[must_use] + fn invalid_nan() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "Invalid value NaN (not a number)").into() + } + /// `time.mktime()`'s `OverflowError` for a wall clock it cannot place on /// the epoch: `mktime argument out of range`. #[must_use] @@ -1211,6 +1268,20 @@ pub(crate) trait ExcTypeExt: Sized { SimpleException::new(ExcType::MemoryError, None).into() } + /// Creates the OverflowError CPython raises when `str * n` would exceed + /// `Py_ssize_t` bytes (`'ab' * 2**62`). + #[must_use] + fn repeated_string_too_long() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "repeated string is too long").into() + } + + /// Creates the OverflowError CPython raises when `bytes * n` would exceed + /// `Py_ssize_t` bytes (`b'ab' * 2**62`). + #[must_use] + fn repeated_bytes_too_long() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "repeated bytes are too long").into() + } + /// Creates the ValueError `itertools.islice` raises for a non-positive or /// non-integer `step`. #[must_use] @@ -1720,22 +1791,35 @@ pub(crate) trait ExcTypeExt: Sized { /// Creates an ImportError for when a name cannot be imported from a module. /// - /// Matches CPython's format for built-in modules: + /// Matches CPython's format, which names the file a module was loaded from: /// `ImportError: cannot import name 'name' from 'module' (unknown location)` /// /// Sets `hide_caret: true` because CPython doesn't show carets for import errors. #[must_use] - fn cannot_import_name(name: &str, module_name: &str) -> RunError { - let exc = SimpleException::new_msg( - ExcType::ImportError, - format!("cannot import name '{name}' from '{module_name}' (unknown location)"), - ); - RunError::Exc(ExceptionRaise { - exc, - frame: None, - snippet_frame: None, - hide_caret: true, - }) + fn cannot_import_name(name: &str, module_name: &str, origin: Option<&str>) -> RunError { + let origin = origin.unwrap_or("unknown location"); + import_error_without_caret(format!("cannot import name '{name}' from '{module_name}' ({origin})")) + } + + /// The `RuntimeError` for a host answering anything but an `import` call + /// with a module file. + #[must_use] + fn module_file_for_non_import() -> RunError { + SimpleException::new_msg( + ExcType::RuntimeError, + "only an import can be answered with a module file", + ) + .into() + } + + /// The `ImportError` for `from module import name` while `module`'s body is + /// still running, CPython's hint at a circular import. + #[must_use] + fn cannot_import_name_partial(name: &str, module_name: &str, origin: &str) -> RunError { + import_error_without_caret(format!( + "cannot import name '{name}' from partially initialized module '{module_name}' \ + (most likely due to a circular import) ({origin})" + )) } /// Creates a ValueError when an integer is too large to convert to a decimal string. @@ -2590,7 +2674,7 @@ impl ExcTypeExt for ExcType { /// /// This is used for performance reasons for common exception patterns. /// Exception messages use `String` for owned storage. -#[derive(Debug, Clone, PartialEq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Debug, PartialEq, Hash, serde::Serialize, serde::Deserialize)] pub(crate) struct SimpleException { exc_type: ExcType, arg: Option, @@ -2598,6 +2682,41 @@ pub(crate) struct SimpleException { /// through catch/re-raise so it reaches the public `MontyException` when /// the exception escapes the sandbox. data: ExcData, + /// The chained exceptions; only the heap-resident object owns them. Boxed + /// because most exceptions have none and `HeapData` has a size ceiling. + #[serde(default)] + chain: Option>, +} + +/// `Clone` rebuilds the copy without its [`ExceptionChain`]: a raw `HeapId` copied +/// out of the heap object would be a second, uncounted owner. The chain lives on the +/// raised heap object, which `raise` reuses, so it is only lost where an exception is +/// rebuilt from a copy, such as after a nested synchronous call. +impl Clone for SimpleException { + fn clone(&self) -> Self { + Self { + exc_type: self.exc_type, + arg: self.arg.clone(), + data: self.data.clone(), + chain: None, + } + } +} + +/// An exception's `__cause__`, `__context__` and `__suppress_context__`. +/// +/// Both references are owned by the heap-resident exception and released by its +/// `py_dec_ref_ids`. Exceptions stay GC leaves, so a cycle through them +/// (`raise e from e`) is only reclaimed with the session; `__context__` links +/// that would loop are cut when attached, as CPython cuts them. +#[derive(Debug, Default, PartialEq, Hash, serde::Serialize, serde::Deserialize)] +pub(crate) struct ExceptionChain { + /// Owned: set by `raise ... from`. + cause: Option, + /// Owned: the exception being handled when this one was raised. + context: Option, + /// Set by `raise ... from`, hiding the context in a chained traceback. + suppress_context: bool, } impl fmt::Display for SimpleException { @@ -2611,6 +2730,7 @@ impl From for SimpleException { exc_type: exc.exc_type(), data: exc.take_data(), arg: exc.into_message(), + chain: None, } } } @@ -2623,6 +2743,7 @@ impl SimpleException { exc_type, arg, data: ExcData::None, + chain: None, } } @@ -2633,6 +2754,7 @@ impl SimpleException { exc_type, arg: Some(arg.to_string()), data: ExcData::None, + chain: None, } } @@ -2643,6 +2765,7 @@ impl SimpleException { exc_type, arg: None, data: ExcData::None, + chain: None, } } @@ -2673,15 +2796,43 @@ impl SimpleException { (_, None) => String::new(), } } -} -impl<'h> HeapRead<'h, SimpleException> { - pub(crate) fn py_type(&self, vm: &VM<'h>) -> Type { - Type::Exception(self.get(vm.heap).exc_type) + /// The `__cause__`, borrowed. + pub(crate) fn cause(&self) -> Option { + self.chain.as_ref().and_then(|chain| chain.cause) + } + + /// The `__context__`, borrowed. + pub(crate) fn context(&self) -> Option { + self.chain.as_ref().and_then(|chain| chain.context) + } + + /// `__suppress_context__`: whether this exception was raised with `from`. + pub(crate) fn suppress_context(&self) -> bool { + self.chain.as_ref().is_some_and(|chain| chain.suppress_context) + } + + /// Replaces the cause with an owned reference and sets `__suppress_context__`, + /// returning the previous owned cause for the caller to release. + pub(crate) fn set_cause(&mut self, cause: Option) -> Option { + let chain = self.chain.get_or_insert_default(); + chain.suppress_context = true; + mem::replace(&mut chain.cause, cause) + } + + /// Replaces the context with an owned reference, returning the previous owned + /// context for the caller to release. + pub(crate) fn set_context(&mut self, context: Option) -> Option { + mem::replace(&mut self.chain.get_or_insert_default().context, context) + } + + /// Both owned chain references, for `py_dec_ref_ids`. + pub(crate) fn owned_chain_ids(&self) -> impl Iterator { + self.chain + .iter() + .flat_map(|chain| chain.cause.into_iter().chain(chain.context)) } -} -impl SimpleException { /// Returns the exception formatted as Python would repr it. pub fn py_repr_fmt(&self, f: &mut impl Write) -> fmt::Result { let type_str: &'static str = self.exc_type.into(); @@ -2718,27 +2869,46 @@ impl SimpleException { } impl<'h> HeapRead<'h, SimpleException> { - /// Gets an attribute from this exception. - /// - /// Handles the `.args` attribute by allocating a tuple containing the message. - /// Returns `None` for all other attributes. + pub(crate) fn py_type(&self, vm: &VM<'h>) -> Type { + Type::Exception(self.get(vm.heap).exc_type) + } + + /// Gets an attribute from this exception: `args` (a tuple of the message, if + /// any), `__cause__`, `__context__` and `__suppress_context__`. Returns `None` + /// for all other attributes. pub fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> Option { - // Fast path: interned strings can be matched by ID - let is_args = attr - .static_string(vm.interns) - .map_or_else(|| attr.as_str(vm.interns) == "args", |ss| ss == StaticStrings::Args); - - if is_args { - // Construct tuple with 0 or 1 elements based on whether arg exists - let elements = if let Some(arg_str) = &self.get(vm.heap).arg { - smallvec![allocate_string(arg_str.as_str(), vm.heap)] - } else { - smallvec![] - }; - Some(CallResult::Value(allocate_tuple(elements, vm.heap))) - } else { - None + // Interned names match by ID; only `args` can also arrive as a dynamic string. + let name = attr.static_string(vm.interns); + let exc = self.get(vm.heap); + let value = match name { + Some(StaticStrings::DunderCause) => chained_value(exc.cause(), vm), + Some(StaticStrings::DunderContext) => chained_value(exc.context(), vm), + Some(StaticStrings::DunderSuppressContext) => Value::Bool(exc.suppress_context()), + Some(StaticStrings::Args) => args_tuple(exc.arg.as_deref(), vm), + None if attr.as_str(vm.interns) == "args" => args_tuple(exc.arg.as_deref(), vm), + _ => return None, + }; + Some(CallResult::Value(value)) + } +} + +/// `exc.args`: a tuple holding the message, or empty. +fn args_tuple(arg: Option<&str>, vm: &VM<'_>) -> Value { + let elements = match arg { + Some(arg) => smallvec![allocate_string(arg, vm.heap)], + None => smallvec![], + }; + allocate_tuple(elements, vm.heap) +} + +/// A new reference to a chained exception, or `None`. +fn chained_value(id: Option, vm: &VM<'_>) -> Value { + match id { + Some(id) => { + vm.heap.inc_ref(id); + Value::Ref(id) } + None => Value::None, } } @@ -2791,17 +2961,15 @@ impl ExceptionRaise { /// this sets its name instead of creating a new parent. This happens when the error /// is raised from a namespace lookup - the initial frame has the position but not /// the function name, which gets filled in as the error propagates. - pub(crate) fn add_caller_frame(&mut self, position: CodeRange, name: StringId) { - self.add_caller_frame_inner(position, name, false); - } - - fn add_caller_frame_inner(&mut self, position: CodeRange, name: StringId, hide_caret: bool) { + /// + /// `hide_caret` omits the added frame's carets, as CPython does under an + /// `import` whose module body raised; a nameless frame keeps its own. + pub(crate) fn add_caller_frame(&mut self, position: CodeRange, name: StringId, hide_caret: bool) { if let Some(ref mut frame) = self.frame { // If innermost frame has no name, set it instead of adding a parent // This handles errors from namespace lookups which create nameless frames if frame.frame_name.is_none() { frame.frame_name = Some(name); - frame.hide_caret = hide_caret; return; } // Find the outermost frame (the one with no parent) and add the new frame as its parent @@ -2861,8 +3029,10 @@ impl ExceptionRaise { let sm_idx = if let Some(i) = cache.iter().position(|(k, _)| *k == fname_id) { i } else { - let src = - eval_source.unwrap_or_else(|| source_for(interns.get_filename(fname_id)).unwrap_or("")); + // An imported file also carries its own source, but shows its lines. + let src = eval_source + .or_else(|| interns.file_source(fname_id)) + .unwrap_or_else(|| source_for(interns.get_filename(fname_id)).unwrap_or("")); cache.push((fname_id, SourceMap::new(src))); cache.len() - 1 }; @@ -3046,6 +3216,16 @@ fn no_module_named(module_name: &str) -> String { format!("No module named '{module_name}'") } +/// An `ImportError` shown without carets, as CPython shows import errors. +fn import_error_without_caret(msg: String) -> RunError { + RunError::Exc(ExceptionRaise { + exc: SimpleException::new_msg(ExcType::ImportError, msg), + frame: None, + snippet_frame: None, + hide_caret: true, + }) +} + /// Formats a list of parameter names for error messages, matching CPython's /// `format_missing` joining (note the Oxford comma for three or more names). /// diff --git a/crates/bashkit-monty/src/expressions.rs b/crates/bashkit-monty/src/expressions.rs index 275ae1d94..5b7de2bdf 100644 --- a/crates/bashkit-monty/src/expressions.rs +++ b/crates/bashkit-monty/src/expressions.rs @@ -665,7 +665,11 @@ pub enum Node { Pass, Expr(ExprLoc), Return(Option), - Raise(Option), + /// `raise exc from cause`; a bare `raise` has neither. + Raise { + exc: Option, + cause: Option, + }, Assert { test: ExprLoc, msg: Option, @@ -975,6 +979,12 @@ pub struct PreparedFunctionDef { /// When true, calling this function creates a `Coroutine` object instead of /// immediately pushing a frame. pub is_async: bool, + /// The prepared `__annotate__(format)` of an annotated `def`, compiled as a + /// nested function and recorded on the [`Function`](crate::function::Function). + pub annotate: Option>, + /// Whether this is a synthesized `__annotate__`, named so in tracebacks + /// whatever a class body binds it as (`__annotate_func__`). + pub is_annotate: bool, } /// Type alias for prepared AST nodes (output of prepare phase). diff --git a/crates/bashkit-monty/src/frozen.rs b/crates/bashkit-monty/src/frozen.rs index 0dd48116d..5fdf104c4 100644 --- a/crates/bashkit-monty/src/frozen.rs +++ b/crates/bashkit-monty/src/frozen.rs @@ -8,16 +8,17 @@ use monty_types::CompileOptions; use serde::{Deserialize, Serialize}; use crate::{ + annotations, args::ArgValues, builtins::next, bytecode::{CallResult, Compiler, VM}, exception_private::RunResult, intern::{CompileInterns, FunctionId, Interns}, - modules::functools, + modules::{functools, typing}, name_map::NameMap, parse::parse_with_interner, prepare::prepare_with_existing_names, - types::{iter, lru_cache}, + types::{forward_ref, generic_alias, iter, lru_cache}, }; /// Identifies an internal implementation with one authoritative source definition. @@ -36,6 +37,15 @@ pub(crate) enum FrozenFunction { /// Return a default when a suspendable user `__next__` method is exhausted. #[serde(rename = "builtins.next_default")] NextDefault, + /// Evaluate annotations for `annotationlib.get_annotations` and `typing.get_type_hints`. + #[serde(rename = "annotationlib.get_annotations")] + GetAnnotations, + /// `ForwardRef.evaluate()`, applying the format's rules to one evaluation. + #[serde(rename = "annotationlib.ForwardRef.evaluate")] + ForwardRefEvaluate, + /// Evaluate and cache a class's `__annotations__` from its `__annotate__`. + #[serde(rename = "type.__annotations__")] + ClassAnnotations, } impl FrozenFunction { @@ -46,10 +56,11 @@ impl FrozenFunction { let mut overlay = CompileInterns::new(interns); let index = overlay.functions_len(); let mut globals = NameMap::new(); + let parsed = + parse_with_interner(source, "", &mut overlay, false).map_err(|e| e.into_run_error(source))?; let nodes = - parse_with_interner(source, "", &mut overlay).map_err(|e| e.into_run_error(source))?; - let nodes = prepare_with_existing_names(nodes, &overlay, &mut globals).map_err(|e| e.into_run_error(source))?; - Compiler::compile_module(&nodes, &mut overlay, &globals, CompileOptions::default()) + prepare_with_existing_names(parsed.nodes, &overlay, &mut globals).map_err(|e| e.into_run_error(source))?; + Compiler::compile_module(&nodes, &mut overlay, &globals, CompileOptions::default(), false) .map_err(|e| e.into_run_error(source))?; assert_eq!( overlay.functions_len(), @@ -73,6 +84,9 @@ impl FrozenFunction { Self::Iter => iter::ITER_SOURCE, Self::LruCacheMiss => lru_cache::CACHE_MISS_SOURCE, Self::NextDefault => next::NEXT_DEFAULT_SOURCE, + Self::GetAnnotations => typing::GET_ANNOTATIONS_SOURCE, + Self::ForwardRefEvaluate => forward_ref::EVALUATE_SOURCE, + Self::ClassAnnotations => annotations::CLASS_ANNOTATIONS_SOURCE, } } } @@ -82,10 +96,20 @@ impl FrozenFunction { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, strum::Display)] #[strum(serialize_all = "snake_case")] pub(crate) enum FrozenFunctions { + /// Rebuild a generic alias around resolved arguments (see `generic_alias::call_alias_with`). + AliasWith, + /// Cache a class's evaluated `__annotations__` under `__annotations_cache__`. + CacheClassAnnotations, + /// Call an `__annotate__` function in an `annotationlib.Format` (see `annotations::call_annotate_helper`). + CallAnnotate, + /// Evaluate one annotation string in explicit namespaces and name-resolution mode. + EvalHint, /// Call a user `__iter__` without validating its result yet. GetIter, /// Insert a successful result into a cache wrapper. Store, + /// `annotationlib.type_repr`: a type by name, anything else by repr. + TypeRepr, /// Check the result returned by a user `__iter__` method. ValidateIterator, } @@ -93,8 +117,15 @@ pub(crate) enum FrozenFunctions { /// Dispatches private helpers using the same argument ownership rules as public natives. pub(crate) fn call_helper(function: FrozenFunctions, args: ArgValues, vm: &mut VM<'_>) -> RunResult { match function { + FrozenFunctions::AliasWith => generic_alias::call_alias_with(args, vm).map(CallResult::Value), + FrozenFunctions::CacheClassAnnotations => { + annotations::cache_class_annotations_helper(args, vm).map(CallResult::Value) + } + FrozenFunctions::CallAnnotate => annotations::call_annotate_helper(args, vm), + FrozenFunctions::EvalHint => typing::call_eval_hint(args, vm), FrozenFunctions::GetIter => iter::call_get_iter(args, vm), FrozenFunctions::Store => lru_cache::call_store(args, vm).map(CallResult::Value), + FrozenFunctions::TypeRepr => typing::call_type_repr(args, vm).map(CallResult::Value), FrozenFunctions::ValidateIterator => iter::call_validate_iterator(args, vm).map(CallResult::Value), } } diff --git a/crates/bashkit-monty/src/fstring.rs b/crates/bashkit-monty/src/fstring.rs index dcffea803..458f6a0b3 100644 --- a/crates/bashkit-monty/src/fstring.rs +++ b/crates/bashkit-monty/src/fstring.rs @@ -698,7 +698,11 @@ pub fn format_with_spec(value: &Value, spec: &ParsedFormatSpec, vm: &mut VM<'_>) validate_string_spec(spec)?; // `value` is already a `str`, so borrow it directly — no `py_str` // round-trip (which would allocate a fresh heap copy just to drop it). - return format_string(value.to_str(vm)?, spec, &vm.heap.tracker); + return format_string( + value.as_str(vm).expect("string type checked above"), + spec, + &vm.heap.tracker, + ); } // A grouping option (`,`/`_`) is only legal for certain presentation @@ -868,7 +872,7 @@ pub fn format_with_spec(value: &Value, spec: &ParsedFormatSpec, vm: &mut VM<'_>) (_, None) => { let s = value.py_str(vm)?; defer_drop!(s, vm); - format_string(s.to_str(vm)?, spec, &vm.heap.tracker) + format_string(s.as_str(vm).expect("py_str returns str"), spec, &vm.heap.tracker) } // Type mismatch errors diff --git a/crates/bashkit-monty/src/function.rs b/crates/bashkit-monty/src/function.rs index 13dcec560..03cedfb72 100644 --- a/crates/bashkit-monty/src/function.rs +++ b/crates/bashkit-monty/src/function.rs @@ -3,7 +3,13 @@ use std::{ fmt::{self, Write}, }; -use crate::{args::Signature, bytecode::Code, expressions::Identifier, intern::Interns, namespace::NamespaceId}; +use crate::{ + args::Signature, + bytecode::Code, + expressions::Identifier, + intern::{FunctionId, Interns}, + namespace::NamespaceId, +}; /// How an exact positional call can bypass argument binding. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -89,6 +95,10 @@ pub(crate) struct Function { /// than merely checked. #[serde(skip)] exact_positional_call: OnceCell>, + /// The compiled `__annotate__(format)` of an annotated `def` (PEP 649), run + /// for `f.__annotations__` and `typing.get_type_hints()`; `None` when unannotated. + #[serde(rename = "T", default, skip_serializing_if = "Option::is_none")] + pub annotate: Option, /// Compiled body borrowed by active frames, which track body-relative instruction offsets. #[serde(rename = "B")] pub code: Code, @@ -134,10 +144,18 @@ impl Function { defaults_count, is_async, exact_positional_call: OnceCell::new(), + annotate: None, code, } } + /// Attaches the compiled `__annotate__` function. + #[must_use] + pub fn with_annotate(mut self, annotate: Option) -> Self { + self.annotate = annotate; + self + } + /// Returns the binder-free call plan for this function, deriving and /// caching it on first use. pub(crate) fn exact_positional_call(&self) -> Option { @@ -161,13 +179,9 @@ impl Function { } } - /// Writes the Python repr() string for this function to a formatter. + /// Writes the Python repr() string for this function to a formatter, as + /// CPython does: ``, with the name unquoted. pub fn py_repr_fmt(&self, f: &mut W, interns: &Interns, py_id: impl fmt::LowerHex) -> fmt::Result { - write!( - f, - "", - interns.get_str(self.name.name_id), - py_id - ) + write!(f, "", interns.get_str(self.name.name_id), py_id) } } diff --git a/crates/bashkit-monty/src/heap/mod.rs b/crates/bashkit-monty/src/heap/mod.rs index 307d273eb..d44a503c5 100644 --- a/crates/bashkit-monty/src/heap/mod.rs +++ b/crates/bashkit-monty/src/heap/mod.rs @@ -2093,21 +2093,10 @@ fn for_each_child_id(data: &HeapData, mut on_child: F) { HeapData::Partial(partial) => partial.for_each_child_id(on_child), HeapData::GenericAlias(alias) => alias.for_each_child_id(on_child), HeapData::Union(union) => union.for_each_child_id(on_child), + HeapData::ForwardRef(forward_ref) => forward_ref.for_each_child_id(on_child), HeapData::LruCache(cache) => cache.for_each_child_id(on_child), - HeapData::Module(m) => { - // Module attrs can contain references to heap values - if !m.has_refs() { - return; - } - for (k, v) in m.attrs() { - if let Value::Ref(id) = k { - on_child(*id); - } - if let Value::Ref(id) = v { - on_child(*id); - } - } - } + // Attrs and, for a file module, its namespace dict. + HeapData::Module(m) => m.for_each_child_id(on_child), HeapData::Coroutine(coro) => { // Add namespace values that are heap references for value in &coro.namespace { @@ -2195,6 +2184,8 @@ fn for_each_child_id(data: &HeapData, mut on_child: F) { // Mirror `py_dec_ref_ids_for_data`: both own references to decimal contexts. HeapData::DecimalSignalDict(dict) => on_child(dict.context_id()), HeapData::DecimalContextManager(manager) => manager.context_ids().for_each(on_child), + // The owned `__cause__` / `__context__`; exceptions are still not GC-tracked. + HeapData::Exception(exc) => exc.owned_chain_ids().for_each(on_child), // Leaf types with no heap references _ => {} } @@ -2257,6 +2248,7 @@ fn py_dec_ref_ids_for_data(data: &mut HeapData, stack: &mut Vec) { HeapData::Partial(partial) => partial.py_dec_ref_ids(stack), HeapData::GenericAlias(alias) => alias.py_dec_ref_ids(stack), HeapData::Union(union) => union.py_dec_ref_ids(stack), + HeapData::ForwardRef(forward_ref) => forward_ref.py_dec_ref_ids(stack), HeapData::LruCache(cache) => cache.py_dec_ref_ids(stack), HeapData::Module(m) => m.py_dec_ref_ids(stack), HeapData::Coroutine(coro) => { @@ -2328,6 +2320,8 @@ fn py_dec_ref_ids_for_data(data: &mut HeapData, stack: &mut Vec) { // Release the owned decimal context references (mirrors `for_each_child_id`). HeapData::DecimalSignalDict(dict) => dict.py_dec_ref_ids(stack), HeapData::DecimalContextManager(manager) => manager.py_dec_ref_ids(stack), + // Release the owned `__cause__` / `__context__` references (mirrors `for_each_child_id`). + HeapData::Exception(exc) => exc.py_dec_ref_ids(stack), // other types have no nested heap references _ => {} } diff --git a/crates/bashkit-monty/src/heap_data.rs b/crates/bashkit-monty/src/heap_data.rs index 428204b45..e4fde43cd 100644 --- a/crates/bashkit-monty/src/heap_data.rs +++ b/crates/bashkit-monty/src/heap_data.rs @@ -10,6 +10,7 @@ use std::{ use monty_types::ExcType; use crate::{ + annotations, args::ArgValues, asyncio::{Awaiter, Coroutine, ExternalFuture, ExternalFutureState, GatherFuture, GatherState}, bytecode::{CallResult, VM}, @@ -166,6 +167,8 @@ macro_rules! heap_payloads { GenericAlias(inline $crate::types::GenericAlias), /// A `typing.Union` such as `int | None`. Union(inline $crate::types::Union), + /// An `annotationlib.ForwardRef`, also the stringifier a `FORWARDREF` evaluation composes. + ForwardRef(boxed $crate::types::ForwardRef), /// A `random.Random` generator instance. Random(boxed $crate::types::Random), /// A `functools.lru_cache` / `functools.cache` wrapper. @@ -272,6 +275,7 @@ impl HeapData { | Self::Partial(_) | Self::GenericAlias(_) | Self::Union(_) + | Self::ForwardRef(_) | Self::LruCache(_) | Self::Csv(_) => true, // Leaf types, plus iterators whose heap refs only point at leaves and so @@ -350,6 +354,7 @@ impl HeapData { Self::HashObject(hash) => hash.algorithm().py_type(), Self::GenericAlias(_) => Type::GenericAlias, Self::Union(_) => Type::Union, + Self::ForwardRef(_) => Type::ForwardRef, Self::LruCache(_) => Type::LruCacheWrapper, Self::DictKeysView(_) => Type::DictKeys, Self::DictItemsView(_) => Type::DictItems, @@ -554,6 +559,19 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Closure> { let defaults = closure.defaults.iter().map(|v| v.clone_with_heap(vm)).collect(); call_def(func_id, &cells, defaults, globals, args, vm) } + + fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> RunResult> { + let closure = self.get(vm.heap); + let (func_id, globals) = (closure.func_id, closure.globals); + annotations::function_getattr(func_id, globals, attr.as_str(vm.interns), vm).transpose() + } + + fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult { + let closure = self.get(vm.heap); + let (func_id, globals) = (closure.func_id, closure.globals); + annotations::function_call_attr(func_id, globals, attr.as_str(vm.interns), args, vm) + .unwrap_or_else(|| Err(ExcType::attribute_error("function", attr.as_str(vm.interns)))) + } } impl<'h> PyTrait<'h> for HeapObjectRead<'h, FunctionDefaults> { @@ -595,6 +613,19 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, FunctionDefaults> { let defaults = function.defaults.iter().map(|v| v.clone_with_heap(vm)).collect(); call_def(func_id, &[], defaults, globals, args, vm) } + + fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> RunResult> { + let function = self.get(vm.heap); + let (func_id, globals) = (function.func_id, function.globals); + annotations::function_getattr(func_id, globals, attr.as_str(vm.interns), vm).transpose() + } + + fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult { + let function = self.get(vm.heap); + let (func_id, globals) = (function.func_id, function.globals); + annotations::function_call_attr(func_id, globals, attr.as_str(vm.interns), args, vm) + .unwrap_or_else(|| Err(ExcType::attribute_error("function", attr.as_str(vm.interns)))) + } } /// Hashes a function identity, the hash both `def` representations report. @@ -605,8 +636,10 @@ fn hash_func_id(func_id: FunctionId) -> HashValue { } impl HeapItem for SimpleException { - fn py_dec_ref_ids(&mut self, _stack: &mut Vec) { - // Exceptions don't contain heap references + fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + // Only the chain holds references; they are always exceptions, so an + // exception still cannot reach a container and stays a GC leaf. + stack.extend(self.owned_chain_ids()); } } @@ -713,6 +746,7 @@ macro_rules! heap_read_output_py_trait_forward { Self::HashObject($value) => $body, Self::GenericAlias($value) => $body, Self::Union($value) => $body, + Self::ForwardRef($value) => $body, Self::LruCache($value) => $body, Self::Tuple($value) => $body, Self::NamedTuple($value) => $body, @@ -891,6 +925,14 @@ impl<'h> PyTrait<'h> for HeapReadOutput<'h> { heap_read_output_py_trait_forward!(self, |value| value.py_iadd_impl(other, vm), else Ok(false)) } + fn py_imul_impl(&mut self, other: &Value, vm: &mut VM<'h>) -> RunResult { + heap_read_output_py_trait_forward!(self, |value| value.py_imul_impl(other, vm), else Ok(false)) + } + + fn py_ixor_impl(&mut self, other: &Value, vm: &mut VM<'h>) -> RunResult { + heap_read_output_py_trait_forward!(self, |value| value.py_ixor_impl(other, vm), else Ok(false)) + } + fn py_isub_impl(&mut self, other: &Value, vm: &mut VM<'h>) -> RunResult { heap_read_output_py_trait_forward!(self, |value| value.py_isub_impl(other, vm), else Ok(false)) } @@ -922,6 +964,9 @@ impl<'h> PyTrait<'h> for HeapReadOutput<'h> { } fn py_set_attr(&mut self, name: &EitherStr, value: Value, vm: &mut VM<'h>) -> RunResult<()> { + if let Self::Module(module) = self { + return module.py_set_attr(name, value, vm); + } heap_read_output_py_trait_forward!( self, |item| item.py_set_attr(name, value, vm), @@ -1010,6 +1055,7 @@ impl<'h> PyTrait<'h> for HeapReadOutput<'h> { | Self::HashObject(_) | Self::GenericAlias(_) | Self::Union(_) + | Self::ForwardRef(_) | Self::LruCache(_) | Self::Cell(_) | Self::Exception(_) diff --git a/crates/bashkit-monty/src/identity.rs b/crates/bashkit-monty/src/identity.rs index 8812d7619..fac0abadf 100644 --- a/crates/bashkit-monty/src/identity.rs +++ b/crates/bashkit-monty/src/identity.rs @@ -10,7 +10,7 @@ use crate::{ builtins::Builtins, heap::{Heap, HeapId}, modules::ModuleFunctions, - types::{LongInt, Property}, + types::{LongInt, Property, inline_str::InlineStr}, value::{Marker, Value}, }; @@ -42,6 +42,8 @@ pub(crate) enum Identity { Float(u64), /// Identity of an interned string. InternString(usize), + /// Content identity of a short string stored inline. + InlineString(InlineStr), /// Identity of an interned bytes value. InternBytes(usize), /// Identity of an interned long integer literal. @@ -72,6 +74,7 @@ impl Identity { Value::Int(value) => Self::Int(*value), Value::Float(value) => Self::Float(value.to_bits()), Value::InternString(id) => Self::InternString(id.index()), + Value::InlineString(text) => Self::InlineString(*text), Value::InternBytes(id) => Self::InternBytes(id.index()), Value::InternLongInt(id) => Self::InternLongInt(id.index()), Value::Builtin(builtin) => Self::Builtin(*builtin), @@ -102,6 +105,7 @@ impl Identity { | Self::InternLongInt(index) | Self::DefFunction(index) | Self::Heap(index) => u128::try_from(*index).expect("usize fits in u128"), + Self::InlineString(text) => bytes_payload(text.as_str().as_bytes()), Self::Builtin(value) => fixed_serde_payload(value), Self::ModuleFunction(value) => fixed_serde_payload(value), Self::Marker(value) => fixed_serde_payload(value), @@ -128,6 +132,7 @@ impl Identity { Self::Int(_) => 5, Self::Float(_) => 6, Self::InternString(_) => 7, + Self::InlineString(_) => 17, Self::InternBytes(_) => 8, Self::InternLongInt(_) => 9, Self::Builtin(_) => 10, diff --git a/crates/bashkit-monty/src/intern.rs b/crates/bashkit-monty/src/intern.rs index 7b14f8443..95f5249e1 100644 --- a/crates/bashkit-monty/src/intern.rs +++ b/crates/bashkit-monty/src/intern.rs @@ -39,6 +39,7 @@ use crate::{ frozen::FrozenFunction, function::Function, hash::{HashValue, RESERVED_STRING_HASHES, WithHash, hash_python_str}, + prepare::SnippetNames, }; /// Index into the string interner's storage. @@ -575,6 +576,8 @@ pub enum StaticStrings { /// `typing.Annotated` marker. #[strum(serialize = "Annotated")] Annotated, + /// The `annotationlib` module. + Annotationlib, /// `typing.Any` marker. #[strum(serialize = "Any")] Any, @@ -588,6 +591,8 @@ pub enum StaticStrings { AppendText, /// `deque.appendleft()` method. Appendleft, + /// `arg` parameter of `annotationlib.ForwardRef()`. + Arg, /// `BaseException.args` attribute. Args, /// `sys.argv` attribute. @@ -990,9 +995,28 @@ pub enum StaticStrings { Dump, /// `json.dumps()` function. Dumps, + /// `__annotate__` — a function's PEP 649 annotate function, and the key a + /// namespace handed to `type()` may store a class's under. + #[strum(serialize = "__annotate__")] + DunderAnnotate, + /// `__annotate_func__` — where a compiled class body stores its `__annotate__`. + #[strum(serialize = "__annotate_func__")] + DunderAnnotateFunc, + /// `__annotations__` — a class's stored annotations dict. + #[strum(serialize = "__annotations__")] + DunderAnnotations, + /// `__annotations_cache__` — a class's evaluated annotations, cached on first access. + #[strum(serialize = "__annotations_cache__")] + DunderAnnotationsCache, /// `__args__` of a `types.GenericAlias`. #[strum(serialize = "__args__")] DunderArgs, + /// `__cause__` of an exception, set by `raise ... from`. + #[strum(serialize = "__cause__")] + DunderCause, + /// `__context__` of an exception: the one being handled when it was raised. + #[strum(serialize = "__context__")] + DunderContext, /// `__delattr__` — the frozen-dataclass hook `@dataclass` generates. #[strum(serialize = "__delattr__")] DunderDelattr, @@ -1003,6 +1027,18 @@ pub enum StaticStrings { /// `__eq__` — written into a class namespace by `@dataclass`. #[strum(serialize = "__eq__")] DunderEq, + /// `__forward_arg__` — the source text of an `annotationlib.ForwardRef`. + #[strum(serialize = "__forward_arg__")] + DunderForwardArg, + /// `__forward_is_argument__` attribute of `annotationlib.ForwardRef`. + #[strum(serialize = "__forward_is_argument__")] + DunderForwardIsArgument, + /// `__forward_is_class__` attribute of `annotationlib.ForwardRef`. + #[strum(serialize = "__forward_is_class__")] + DunderForwardIsClass, + /// `__forward_module__` attribute of `annotationlib.ForwardRef`. + #[strum(serialize = "__forward_module__")] + DunderForwardModule, /// `__getnewargs__` — the copy/pickle hook on named tuples. #[strum(serialize = "__getnewargs__")] DunderGetnewargs, @@ -1018,6 +1054,9 @@ pub enum StaticStrings { /// `__main__`, the `__name__` of the module being run. #[strum(serialize = "__main__")] DunderMain, + /// `__metadata__` of `typing.Annotated[T, *metadata]`. + #[strum(serialize = "__metadata__")] + DunderMetadata, /// `defaultdict.__missing__` method. #[strum(serialize = "__missing__")] DunderMissing, @@ -1030,6 +1069,9 @@ pub enum StaticStrings { /// `__origin__` of a `types.GenericAlias`. #[strum(serialize = "__origin__")] DunderOrigin, + /// `__owner__` attribute of `annotationlib.ForwardRef`. + #[strum(serialize = "__owner__")] + DunderOwner, /// `__parameters__` of a `types.GenericAlias`. #[strum(serialize = "__parameters__")] DunderParameters, @@ -1039,9 +1081,15 @@ pub enum StaticStrings { /// `__repr__` — written into a class namespace by `@dataclass`. #[strum(serialize = "__repr__")] DunderRepr, + /// `__resolved_str__` attribute of `annotationlib.ForwardRef`. + #[strum(serialize = "__resolved_str__")] + DunderResolvedStr, /// `__setattr__` — the frozen-dataclass hook `@dataclass` generates. #[strum(serialize = "__setattr__")] DunderSetattr, + /// `__suppress_context__` of an exception, set by `raise ... from`. + #[strum(serialize = "__suppress_context__")] + DunderSuppressContext, /// `decimal.__version__` attribute. #[strum(serialize = "__version__")] DunderVersion, @@ -1101,6 +1149,10 @@ pub enum StaticStrings { Escape, /// `escapechar` dialect attribute and `csv` format parameter. Escapechar, + /// `eval_str` parameter of `annotationlib.get_annotations()`. + EvalStr, + /// `ForwardRef.evaluate()` method. + Evaluate, /// `csv.excel` dialect. Excel, /// `csv.excel_tab` dialect. @@ -1171,6 +1223,8 @@ pub enum StaticStrings { Filename, /// `zip_longest(fillvalue=...)` keyword. Fillvalue, + /// `fnmatch.filter()` function. + Filter, /// `itertools.filterfalse()` function. Filterfalse, /// Value of `sys.version_info.releaselevel`. @@ -1201,6 +1255,10 @@ pub enum StaticStrings { Fma, /// `math.fmod()` function. Fmod, + /// Module name for `import fnmatch`, and its `fnmatch()` function. + Fnmatch, + /// `fnmatch.fnmatchcase()` function. + Fnmatchcase, /// `datetime` / `time` `fold` attribute and constructor kwarg. Fold, /// `foldspaces` parameter of `base64.a85encode()` / `a85decode()`. @@ -1212,6 +1270,15 @@ pub enum StaticStrings { Followlinks, /// Kwarg name `format` — `date.strftime(format=...)`, `datetime.strftime(format=...)`. Format, + /// The `annotationlib.Format` class. + #[strum(serialize = "Format")] + FormatClass, + /// `annotationlib.ForwardRef`, also exported by `typing`. + #[strum(serialize = "ForwardRef")] + ForwardRef, + /// `annotationlib.Format.FORWARDREF` member. + #[strum(serialize = "FORWARDREF")] + Forwardref, /// `fp` parameter of `json.load()` / `json.dump()`. Fp, /// `math.frexp()` function. @@ -1227,6 +1294,8 @@ pub enum StaticStrings { Fromisoformat, /// `dict.fromkeys()` classmethod. Fromkeys, + /// `date.fromtimestamp()` / `datetime.fromtimestamp()` classmethod. + Fromtimestamp, /// `@dataclass(frozen=...)`. Frozen, /// `dataclasses.FrozenInstanceError` exception. @@ -1266,8 +1335,12 @@ pub enum StaticStrings { Generic, /// `dict.get()` method. Get, + /// `annotationlib.get_annotations()` function. + GetAnnotations, /// `csv.get_dialect()` function. GetDialect, + /// `typing.get_type_hints()` function. + GetTypeHints, /// `os.path.getatime()` function. Getatime, /// `decimal.getcontext()` function. @@ -1290,6 +1363,8 @@ pub enum StaticStrings { Getstate, /// `Path.glob()` method — yields a host scan. Glob, + /// `globalns` parameter of `typing.get_type_hints()`. + Globalns, /// `globals` parameter of eval/exec. Globals, /// `time.gmtime()` function. @@ -1362,6 +1437,8 @@ pub enum StaticStrings { Ignorechars, /// `complex.imag` attribute. Imag, + /// `include_extras` parameter of `typing.get_type_hints()`. + IncludeExtras, /// `binascii.Incomplete` exception class. #[strum(serialize = "Incomplete")] IncompleteClass, @@ -1403,6 +1480,10 @@ pub enum StaticStrings { InvalidOperation, /// `Path.is_absolute()` method, answered without host I/O. IsAbsolute, + /// `is_argument` parameter of `annotationlib.ForwardRef()`. + IsArgument, + /// `is_class` parameter of `annotationlib.ForwardRef()`. + IsClass, /// `dataclasses.is_dataclass()` function. IsDataclass, /// `Path.is_dir()` method — yields a host call. @@ -1567,6 +1648,8 @@ pub enum StaticStrings { Loads, /// `decimal.localcontext()` function. Localcontext, + /// `localns` parameter of `typing.get_type_hints()`. + Localns, /// `locals` parameter of eval/exec. Locals, /// `time.localtime()` function. @@ -1737,6 +1820,8 @@ pub enum StaticStrings { Name, /// The `collections.namedtuple` factory function. Namedtuple, + /// `names` parameter of `fnmatch.filter()`. + Names, /// Kwarg name `ndigits` — `round(ndigits=...)`. Ndigits, /// `typing.Never` marker. @@ -1830,6 +1915,8 @@ pub enum StaticStrings { Overflow, /// Kwarg name `override` — `Decimal.__format__()`. Override, + /// `owner` parameter of `annotationlib.ForwardRef()` and `ForwardRef.evaluate()`. + Owner, /// `pad` parameter of `base64.b85encode()`. #[strum(serialize = "pad")] Pad, @@ -1856,6 +1943,8 @@ pub enum StaticStrings { Partition, /// `Path.parts` property. Parts, + /// `pat` parameter of the `fnmatch` functions. + Pat, /// `password` parameter of `hashlib.pbkdf2_hmac()`. Password, /// Kwarg name `path` — `os.listdir(path=...)`, `os.stat(path=...)`, etc. @@ -2286,6 +2375,9 @@ pub enum StaticStrings { /// `match.string` #[strum(serialize = "string")] StringAttr, + /// `annotationlib.Format.STRING` member. + #[strum(serialize = "STRING")] + StringFormat, /// `strip()` method, shared by `str` and `bytes`. Strip, /// `datetime.strptime()` classmethod. @@ -2408,6 +2500,8 @@ pub enum StaticStrings { Total, /// `timedelta.total_seconds()` method. TotalSeconds, + /// `fnmatch.translate()` function. + Translate, /// Kwarg name `traps` — `decimal.Context()`. Traps, /// `random.triangular()` function. @@ -2426,6 +2520,8 @@ pub enum StaticStrings { /// `typing.TYPE_CHECKING` constant. #[strum(serialize = "TYPE_CHECKING")] TypeChecking, + /// `type_params` parameter of `ForwardRef.evaluate()`. + TypeParams, /// `typing.TypeVar` marker. #[strum(serialize = "TypeVar")] TypeVar, @@ -2511,6 +2607,12 @@ pub enum StaticStrings { Validate, /// Kwarg name `value` — `decimal.Decimal()`. Value, + /// `annotationlib.Format.VALUE` member. + #[strum(serialize = "VALUE")] + ValueFormat, + /// `annotationlib.Format.VALUE_WITH_FAKE_GLOBALS` member. + #[strum(serialize = "VALUE_WITH_FAKE_GLOBALS")] + ValueWithFakeGlobals, /// `dict.values()` method. Values, /// `sys.flags.verbose` field. @@ -2580,6 +2682,8 @@ pub enum StaticStrings { struct InternedString { /// Runtime classification, independent of the string's executor-local ID. static_tag: Option, + // Immutable text needs only one ASCII scan, including after snapshot loading. + ascii: bool, /// Text and its eagerly computed Python hash. text: WithHash, } @@ -2607,6 +2711,7 @@ impl InternedString { fn static_string(value: StaticStrings) -> Self { Self { static_tag: Some(value), + ascii: <&str>::from(value).is_ascii(), text: WithHash::for_str(InternedText::Static(value.into())), } } @@ -2615,6 +2720,7 @@ impl InternedString { fn owned(value: String) -> Self { Self { static_tag: None, + ascii: value.is_ascii(), text: WithHash::for_str(InternedText::Owned(value.into_boxed_str())), } } @@ -2796,6 +2902,9 @@ pub(crate) struct Interns { /// Installed internal implementations by identity, ordered for stable dump bytes. frozen_functions: RefCell>, eval_sources: Entries>, + /// Sources of imported `.py` files, with the virtual paths tracebacks name. + #[serde(default)] + file_sources: Entries, #[serde(skip)] string_id_by_name: RefCell>, #[serde(skip)] @@ -2803,6 +2912,9 @@ pub(crate) struct Interns { /// Prevents runtime insertion or a second compiler from consuming provisional IDs. #[serde(skip)] compiling: Cell, + /// Committed `typing.get_type_hints()` snippets by mode and annotation text. + #[serde(skip)] + hint_snippets: RefCell), FunctionId>>, } impl Default for Interns { @@ -2821,6 +2933,8 @@ struct InternsWire { #[serde(default)] frozen_functions: RefCell>, eval_sources: Entries>, + #[serde(default)] + file_sources: Entries, } impl TryFrom for Interns { @@ -2849,9 +2963,11 @@ impl TryFrom for Interns { functions: wire.functions, frozen_functions: wire.frozen_functions, eval_sources: wire.eval_sources, + file_sources: wire.file_sources, string_id_by_name: RefCell::new(string_id_by_name), static_string_ids: RefCell::new(static_string_ids), compiling: Cell::new(false), + hint_snippets: RefCell::default(), }) } } @@ -2860,6 +2976,16 @@ impl TryFrom for Interns { /// Each snippet has distinct source identity but the same displayed filename. const SOURCE_ID_BASE: usize = 1 << 31; +/// Imported files take the IDs above the snippet range, so each displays its own path. +const FILE_SOURCE_ID_BASE: usize = 3 << 30; + +/// An imported module file: its virtual path and text, for tracebacks. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub(crate) struct FileSource { + path: Arc, + source: Arc, +} + impl Interns { /// Moves session ownership without initializing another interner. pub(crate) fn take(&mut self) -> Self { @@ -2875,9 +3001,11 @@ impl Interns { functions: Entries::default(), frozen_functions: RefCell::default(), eval_sources: Entries::default(), + file_sources: Entries::default(), string_id_by_name: RefCell::default(), static_string_ids: RefCell::default(), compiling: Cell::new(false), + hint_snippets: RefCell::default(), } } @@ -2891,9 +3019,11 @@ impl Interns { functions: Entries::default(), frozen_functions: RefCell::default(), eval_sources: Entries::default(), + file_sources: Entries::default(), string_id_by_name: RefCell::new(AHashMap::with_capacity(capacity)), static_string_ids: RefCell::new(AHashMap::with_capacity(CORE_STATIC_STRINGS.len())), compiling: Cell::new(false), + hint_snippets: RefCell::default(), }; for entry in CORE_ENTRIES.iter() { let value = entry.static_value().expect("core entries are static"); @@ -2916,9 +3046,11 @@ impl Interns { get_str(&self.strings, id) } - /// Resolves a traceback filename, displaying each snippet's source identity as ``. + /// Resolves a traceback filename: a snippet displays as ``, an imported file as its path. pub(crate) fn get_filename(&self, id: StringId) -> &str { - if id.index() >= SOURCE_ID_BASE { + if id.index() >= FILE_SOURCE_ID_BASE { + &self.file_sources[id.index() - FILE_SOURCE_ID_BASE].path + } else if id.index() >= SOURCE_ID_BASE { assert!( id.index() - SOURCE_ID_BASE < self.eval_sources.len(), "invalid snippet source ID" @@ -2952,15 +3084,45 @@ impl Interns { &self.functions[id.index()] } - /// Looks up source by its filename-only ID, never by the displayed text. + /// Looks up snippet source by its filename-only ID, never by the displayed text. pub(crate) fn eval_source(&self, filename: StringId) -> Option<&str> { - filename - .index() - .checked_sub(SOURCE_ID_BASE) + let index = filename.index(); + (index < FILE_SOURCE_ID_BASE) + .then(|| index.checked_sub(SOURCE_ID_BASE)) + .flatten() .and_then(|index| self.eval_sources.get(index)) .map(AsRef::as_ref) } + /// Every snippet source with its filename-only ID, for a dump upgrade that rewrites positions. + pub(crate) fn eval_sources(&self) -> impl Iterator { + self.eval_sources.iter().enumerate().map(|(index, source)| { + let id = StringId((SOURCE_ID_BASE + index).try_into().expect("source ID overflow")); + (id, source.as_ref()) + }) + } + + /// Mutates every committed function. Only a dump upgrade may call this: + /// a running session borrows function code from these entries. + pub(crate) fn for_each_function_mut(&mut self, mut f: impl FnMut(&mut Function)) { + self.functions.for_each_mut(|function| f(function)); + } + + /// Looks up an imported file's source by its filename-only ID. + pub(crate) fn file_source(&self, filename: StringId) -> Option<&str> { + filename + .index() + .checked_sub(FILE_SOURCE_ID_BASE) + .and_then(|index| self.file_sources.get(index)) + .map(|file| &*file.source) + } + + /// Returns ASCII status without rescanning immutable literal text. + #[inline] + pub fn str_is_ascii(&self, id: StringId) -> bool { + id.index() < RESERVED_STRS.len() || self.strings[id.index() - INTERN_STRING_ID_OFFSET].ascii + } + /// Returns the same hash as an equal heap string. #[inline] pub fn str_hash(&self, id: StringId) -> HashValue { @@ -2993,6 +3155,16 @@ impl Interns { self.frozen_functions.borrow_mut().insert(function, id); } + /// The committed snippet that evaluates annotation `text` in mode `names`, if compiled before. + pub(crate) fn hint_snippet(&self, names: SnippetNames, text: &Arc) -> Option { + self.hint_snippets.borrow().get(&(names, Arc::clone(text))).copied() + } + + /// Records a committed annotation snippet for [`Self::hint_snippet`]. + pub(crate) fn set_hint_snippet(&self, names: SnippetNames, text: Arc, id: FunctionId) { + self.hint_snippets.borrow_mut().insert((names, text), id); + } + /// Identifies implementation frames hidden from tracebacks and namespace introspection. pub(crate) fn is_internal_function(&self, id: FunctionId) -> bool { self.frozen_functions.borrow().values().any(|&function| function == id) diff --git a/crates/bashkit-monty/src/intern/compile.rs b/crates/bashkit-monty/src/intern/compile.rs index a33e65977..395d90dc0 100644 --- a/crates/bashkit-monty/src/intern/compile.rs +++ b/crates/bashkit-monty/src/intern/compile.rs @@ -5,7 +5,10 @@ use std::sync::Arc; use ahash::AHashMap; use num_bigint::BigInt; -use super::{BytesId, InternedString, Interns, LongIntId, SOURCE_ID_BASE, StaticStrings, StringId, next_string_id}; +use super::{ + BytesId, FILE_SOURCE_ID_BASE, FileSource, InternedString, Interns, LongIntId, SOURCE_ID_BASE, StaticStrings, + StringId, next_string_id, +}; use crate::{function::Function, hash::WithHash}; /// Compilation tables with final IDs assigned before execution. @@ -27,6 +30,7 @@ struct PendingInterns { long_ints: Vec>, functions: Vec, sources: Vec>, + file_sources: Vec, } impl<'i> CompileInterns<'i> { @@ -72,6 +76,9 @@ impl<'i> CompileInterns<'i> { for source in pending.sources.drain(..) { self.base.eval_sources.push(source); } + for file in pending.file_sources.drain(..) { + self.base.file_sources.push(file); + } } } @@ -204,6 +211,20 @@ impl<'i> CompileInterns<'i> { id } + /// Records an imported file's source; tracebacks display `path` and its source lines. + pub(crate) fn add_file_source(&mut self, path: Arc, source: Arc) -> StringId { + let pending_len = self.pending.as_ref().map_or(0, |pending| pending.file_sources.len()); + let index = FILE_SOURCE_ID_BASE + self.base.file_sources.len() + pending_len; + let id = StringId(index.try_into().expect("source ID overflow")); + let file = FileSource { path, source }; + if let Some(pending) = &mut self.pending { + pending.file_sources.push(file); + } else { + self.base.file_sources.push(file); + } + id + } + /// Appends a compiled function under its final session ID. pub(crate) fn push_function(&mut self, function: Function) -> usize { let index = self.functions_len(); diff --git a/crates/bashkit-monty/src/intern/storage.rs b/crates/bashkit-monty/src/intern/storage.rs index 2dab4d47b..c783c6862 100644 --- a/crates/bashkit-monty/src/intern/storage.rs +++ b/crates/bashkit-monty/src/intern/storage.rs @@ -36,6 +36,17 @@ impl Entries { pub(super) fn iter(&self) -> impl Iterator { (0..self.len()).map(|index| &self[index]) } + + /// Mutates every entry in ID order; only a dump upgrade, which owns the tables, needs this. + pub(super) fn for_each_mut(&mut self, mut f: impl FnMut(&mut T)) { + for index in 0..self.len() { + let mut entry = self + .0 + .entry(HeapId::from_index(index)) + .expect("committed entries are live"); + f(entry.get_mut()); + } + } } impl Default for Entries { diff --git a/crates/bashkit-monty/src/lib.rs b/crates/bashkit-monty/src/lib.rs index e0f2c4f20..438ce38c5 100644 --- a/crates/bashkit-monty/src/lib.rs +++ b/crates/bashkit-monty/src/lib.rs @@ -7,6 +7,7 @@ mod boundary_uuid; mod heap; mod heap_traits; +mod annotations; mod args; mod asyncio; mod builtins; diff --git a/crates/bashkit-monty/src/modules/annotationlib.rs b/crates/bashkit-monty/src/modules/annotationlib.rs new file mode 100644 index 000000000..313b2fe48 --- /dev/null +++ b/crates/bashkit-monty/src/modules/annotationlib.rs @@ -0,0 +1,131 @@ +//! Implementation of the `annotationlib` module. +//! +//! - `Format`: the `VALUE` / `VALUE_WITH_FAKE_GLOBALS` / `FORWARDREF` / `STRING` +//! constants, as plain ints on a class (Monty has no `enum` module) +//! - `ForwardRef`: an annotation kept as source text (see `types/forward_ref.rs`) +//! - `get_annotations()`: an object's annotations evaluated as written, which +//! `typing.get_type_hints()` builds on + +use crate::{ + args::{ArgValues, FromArgs}, + builtins::Builtins, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::{HeapData, HeapId}, + intern::StaticStrings, + modules::{ + ModuleFunctions, + typing::{HintFormat, HintsRequest, HintsTask, collect_hints, namespace_dict}, + }, + types::{BuiltinType, Class, Dict, Module, PyTrait, forward_ref::format_code}, + value::{EitherStr, Value}, +}; + +/// Creates the `annotationlib` module and allocates it on the heap. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Annotationlib, vm.interns); + let format = format_class(vm); + module.set_attr(StaticStrings::FormatClass, format, vm); + module.set_attr( + StaticStrings::ForwardRef, + Value::Builtin(Builtins::Type(BuiltinType::ForwardRef)), + vm, + ); + module.set_attr( + StaticStrings::GetAnnotations, + Value::ModuleFunction(ModuleFunctions::Annotationlib(AnnotationlibFunctions::GetAnnotations)), + vm, + ); + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// `annotationlib` module functions, each a Python-visible callable. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "snake_case")] +pub(crate) enum AnnotationlibFunctions { + GetAnnotations, +} + +/// Dispatches an `annotationlib` module function call. +pub(super) fn call(vm: &mut VM<'_>, function: AnnotationlibFunctions, args: ArgValues) -> RunResult { + match function { + AnnotationlibFunctions::GetAnnotations => get_annotations(vm, args), + } +} + +/// The `Format` class: `VALUE = 1`, `VALUE_WITH_FAKE_GLOBALS = 2`, `FORWARDREF = 3`, +/// `STRING = 4` as plain ints, so `format=Format.STRING` and `format=4` agree. +fn format_class(vm: &mut VM<'_>) -> Value { + let members = [ + (StaticStrings::ValueFormat, Value::Int(1)), + (StaticStrings::ValueWithFakeGlobals, Value::Int(2)), + (StaticStrings::Forwardref, Value::Int(3)), + (StaticStrings::StringFormat, Value::Int(4)), + (StaticStrings::DunderDoc, Value::None), + ]; + let mut namespace = Dict::new(); + for (name, value) in members { + let key = Value::InternString(vm.interns.intern_static(name)); + // Module construction is infallible: interned keys always hash, and a + // handful of entries needs no growth preflight. + namespace + .set_without_growth_check(key, value, vm) + .expect("class attribute keys are interned, so hashing cannot fail"); + } + let name = EitherStr::Interned(vm.interns.intern_static(StaticStrings::FormatClass)); + Value::Ref(vm.heap.allocate(HeapData::Class(Box::new(Class::new(name, namespace))))) +} + +/// Arguments of `get_annotations(obj, *, globals=None, locals=None, eval_str=False, format=Format.VALUE)`. +#[derive(FromArgs)] +#[from_args(name = "get_annotations", style = def)] +struct GetAnnotationsArgs { + obj: Value, + #[from_args(kw_only, default = Value::None)] + globals: Value, + #[from_args(kw_only, default = Value::None)] + locals: Value, + #[from_args(kw_only, default = Value::Bool(false))] + eval_str: Value, + #[from_args(kw_only, default = Value::Int(1))] + format: Value, +} + +/// `annotationlib.get_annotations()`: `obj`'s annotations evaluated where they were +/// written (or as stored, in `STRING` format), without resolving forward references. +fn get_annotations(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let GetAnnotationsArgs { + obj, + globals, + locals, + eval_str, + format, + } = GetAnnotationsArgs::from_args(args, vm)?; + defer_drop!(obj, vm); + defer_drop!(globals, vm); + defer_drop!(locals, vm); + defer_drop!(eval_str, vm); + defer_drop!(format, vm); + + let eval_str = eval_str.py_bool(vm)?; + if eval_str && format_code(format) != Some(1) { + return Err(ExcType::value_error( + "eval_str=True is only supported with format=Format.VALUE", + )); + } + let format = HintFormat::parse(format, false, vm)?; + let globalns = namespace_dict(globals, "get_annotations", "globals", vm)?; + let localns = namespace_dict(locals, "get_annotations", "locals", vm)?; + collect_hints( + obj, + &HintsRequest { + format, + globalns, + localns, + include_extras: true, + task: HintsTask::Annotations { eval_str }, + }, + vm, + ) +} diff --git a/crates/bashkit-monty/src/modules/base64.rs b/crates/bashkit-monty/src/modules/base64.rs index 748385bbb..bc5a22b5c 100644 --- a/crates/bashkit-monty/src/modules/base64.rs +++ b/crates/bashkit-monty/src/modules/base64.rs @@ -1255,8 +1255,7 @@ pub(super) fn decode_input<'a>(value: &'a Value, vm: &'a VM<'_>) -> RunResult(value: &'a Value, vm: &'a VM<'_>, expected: &str) -> RunResult> { - if value.is_str(vm.heap) { - let text = value.to_str(vm)?; + if let Some(text) = value.as_str(vm) { if text.is_ascii() { Ok(Cow::Borrowed(text.as_bytes())) } else { @@ -1331,7 +1330,7 @@ fn assert_len_bytes(bytes: &[u8], expected: usize) -> RunResult<()> { fn assertion_error(value: &Value, vm: &mut VM<'_>) -> RunResult { let repr = value.py_repr(vm)?; defer_drop!(repr, vm); - let message = repr.to_str(vm)?.to_owned(); + let message = repr.as_str(vm).expect("py_repr returns str").to_owned(); Ok(SimpleException::new_msg(ExcType::AssertionError, message).into()) } diff --git a/crates/bashkit-monty/src/modules/binascii.rs b/crates/bashkit-monty/src/modules/binascii.rs index 121d1b643..4afe402d6 100644 --- a/crates/bashkit-monty/src/modules/binascii.rs +++ b/crates/bashkit-monty/src/modules/binascii.rs @@ -501,10 +501,10 @@ fn hex_separator(sep: Option<&Value>, vm: &VM<'_>) -> RunResult> { if length != 1 { Err(value_error("sep must be length 1.")) - } else if sep.is_str(vm.heap) { + } else if let Some(text) = sep.as_str(vm) { // Latin-1, not ASCII: `hexlify` returns bytes, so CPython only rejects // a character that does not fit a byte, under an "ASCII" message. - u8::try_from(u32::from(sep.to_str(vm)?.chars().next().expect("one character"))) + u8::try_from(u32::from(text.chars().next().expect("one character"))) .map(Some) .map_err(|_| value_error("sep must be ASCII.")) } else if is_bytes(sep, vm) { diff --git a/crates/bashkit-monty/src/modules/bisect.rs b/crates/bashkit-monty/src/modules/bisect.rs index f586477eb..4ebddfc0e 100644 --- a/crates/bashkit-monty/src/modules/bisect.rs +++ b/crates/bashkit-monty/src/modules/bisect.rs @@ -159,7 +159,7 @@ fn search(vm: &mut VM<'_>, a: &Value, x: &Value, bounds: (i64, i64), key: &Value } else { let len = a .py_len(vm) - .ok_or_else(|| ExcType::type_error(format!("object of type '{}' has no len()", a.py_type_name(vm))))?; + .ok_or_else(|| ExcType::type_error_no_len(&a.py_type_name(vm)))?; i64::try_from(len).map_err(|_| ExcType::overflow_c_ssize_t())? }; } diff --git a/crates/bashkit-monty/src/modules/collections/counter.rs b/crates/bashkit-monty/src/modules/collections/counter.rs index 3e251b3a7..32d404b53 100644 --- a/crates/bashkit-monty/src/modules/collections/counter.rs +++ b/crates/bashkit-monty/src/modules/collections/counter.rs @@ -17,9 +17,11 @@ use crate::{ bytecode::VM, defer_drop, defer_drop_mut, exception_private::{ExcType, ExcTypeExt, RunResult}, + expressions::CmpOperator, heap::{DropGuard, DropWithContext, HeapData, HeapObjectRead, HeapReadOutput}, py_value::PyValue, resource_checks::check_repeat_size, + sorting::{py_eq_item, py_lt, sort_indices, sort_indices_by}, types::{Dict, List, PyTrait, allocate_tuple, iter::collect_owned_iterable, py_trait::CmpOrder}, value::{VALUE_SIZE, Value}, }; @@ -95,24 +97,6 @@ fn count_holds(lhs: &Value, rhs: &Value, op: CountCmp, vm: &mut VM<'_>) -> RunRe } } -/// Orders two counts for *sorting* (`most_common`, Counter repr), raising the -/// sort's `<` `TypeError` when they are incomparable. -/// -/// Unlike the algebra's [`count_holds`], a `NaN` pair is treated as **equal** -/// here: Python's `sorted`/`heapq` never raise on `NaN`, they just leave it -/// wherever the (ill-defined for `NaN`) ordering happens to place it. -fn count_sort_cmp(lhs: &Value, rhs: &Value, vm: &mut VM<'_>) -> RunResult { - match lhs.py_cmp(rhs, vm)? { - CmpOrder::Ordered(ordering) => Ok(ordering), - CmpOrder::Unordered => Ok(Ordering::Equal), - CmpOrder::Incomparable => Err(ExcType::type_error_ordering( - "<", - &lhs.py_type_name(vm), - &rhs.py_type_name(vm), - )), - } -} - /// Whether a count is strictly greater than zero (the `Counter` algebra keeps /// only positive results). CPython's `_keep_positive` filters with `count > 0`, /// so an unorderable count reports `>` and a `NaN` count is not positive. @@ -333,34 +317,21 @@ pub(crate) fn counter_total<'h>(counter: &HeapObjectRead<'h, Dict>, vm: &mut VM< } /// Orders entry indices for `most_common` / Counter repr: count descending, -/// ties in insertion order (the sort is stable). +/// ties in insertion order, as CPython's `sorted(items, key=count, reverse=True)`. /// /// Takes the counts by value because the comparison needs `&mut VM` (big ints /// live on the heap), which callers cannot hold alongside a `Dict` borrow. /// Consumes `counts`. pub(crate) fn counter_order(counts: Vec, vm: &mut VM<'_>) -> RunResult> { + defer_drop!(counts, vm); + sort_counts(counts, vm) +} + +/// [`counter_order`] over borrowed counts. +fn sort_counts(counts: &[Value], vm: &mut VM<'_>) -> RunResult> { let mut order: Vec = (0..counts.len()).collect(); - // `sort_by` needs an infallible comparator, so a comparison error is stashed - // and reported once the sort finishes; the ordering it produces in that case - // is discarded. - let mut failure = None; - order.sort_by(|&a, &b| { - if failure.is_some() { - return Ordering::Equal; - } - match count_sort_cmp(&counts[b], &counts[a], vm) { - Ok(ordering) => ordering, - Err(e) => { - failure = Some(e); - Ordering::Equal - } - } - }); - counts.drop_with(vm); - match failure { - Some(e) => Err(e), - None => Ok(order), - } + sort_indices(&mut order, counts, true, vm)?; + Ok(order) } /// `Counter.most_common([n])` — a list of `(element, count)` tuples ordered by @@ -392,16 +363,19 @@ pub(crate) fn counter_most_common<'h>( // the snapshot. CPython's `sorted(self.items(), ...)` snapshots the same way. let pairs = counter.clone_all_pairs(vm)?; defer_drop!(pairs, vm); - let counts = pairs.iter().map(|(_, count)| count.clone_with_heap(vm.heap)).collect(); - let order = counter_order(counts, vm)?; - let take = limit.unwrap_or(order.len()).min(order.len()); + let counts: Vec = pairs.iter().map(|(_, count)| count.clone_with_heap(vm.heap)).collect(); + defer_drop!(counts, vm); + let order = match limit { + None => sort_counts(counts, vm)?, + Some(n) => nlargest(n, counts, vm)?, + }; // Below the length, CPython's `heapq.nlargest` compares while iterating the // live dict, so a comparison that resized it raises there. - if take < pairs.len() && counter.get(vm.heap).len() != pairs.len() { + if order.len() < pairs.len() && counter.get(vm.heap).len() != pairs.len() { return Err(ExcType::runtime_error_dict_changed_size()); } - let items = order[..take] + let items = order .iter() .map(|&i| { let (key, count) = &pairs[i]; @@ -414,6 +388,133 @@ pub(crate) fn counter_most_common<'h>( Ok(vm.heap.allocate_as(List::new(items)).into_value()) } +/// Indices of the `n` largest of `counts` (`n > 0`), largest first, picked as CPython's +/// `heapq.nlargest(n, items, key=count)` picks them, making the same comparisons. +/// +/// The comparisons matter when counts are not totally ordered (`NaN`, sets) or cannot be compared at all: the +/// items chosen, their order and the error raised all follow from which pairs are compared, in which order. +fn nlargest(n: usize, counts: &[Value], vm: &mut VM<'_>) -> RunResult> { + if counts.is_empty() { + Ok(Vec::new()) + } else if n == 1 { + // CPython's shortcut: `max()`, which keeps the first of equal counts. + let mut best = 0; + for i in 1..counts.len() { + vm.heap.tracker.check_time_every(i)?; + if vm.cmp_values(CmpOperator::Gt, &counts[i], &counts[best])? { + best = i; + } + } + Ok(vec![best]) + } else if n >= counts.len() { + sort_counts(counts, vm) + } else { + nlargest_heap(n, counts, vm) + } +} + +/// `heapq.nlargest`'s general case for `1 < n < len(counts)`: a min-heap of the best `n` so far. +/// +/// CPython's heap holds `(count, order, item)` tuples, where `order` counts down from 0 so that, of equal counts, +/// the item that entered the heap first ranks higher; tuple comparison never reaches `item`. +fn nlargest_heap(n: usize, counts: &[Value], vm: &mut VM<'_>) -> RunResult> { + let mut heap: Vec = (0..n).map(|i| HeapEntry { index: i, rank: i }).collect(); + heapify(&mut heap, counts, vm)?; + let mut rank = n; + for (i, count) in counts.iter().enumerate().skip(n) { + vm.heap.tracker.check_time_every(i)?; + if py_lt(&counts[heap[0].index], count, vm)? { + heap[0] = HeapEntry { index: i, rank }; + sift_up(&mut heap, 0, counts, vm)?; + rank += 1; + } + } + // CPython's `result.sort(reverse=True)`. + let mut ids: Vec = (0..heap.len()).collect(); + sort_indices_by(&mut ids, true, vm, |a, b, vm| heap[a].lt(heap[b], counts, vm))?; + Ok(ids.into_iter().map(|id| heap[id].index).collect()) +} + +/// One `(count, order, item)` tuple of [`nlargest_heap`], naming the item by its index into the counts. +#[derive(Clone, Copy)] +struct HeapEntry { + index: usize, + /// When the item entered the heap, `0, 1, 2, ...`: CPython's `order` negated. + rank: usize, +} + +impl HeapEntry { + /// Tuple `<`: the counts decide unless they are equal, then the later entry is the lesser. + fn lt(self, other: Self, counts: &[Value], vm: &mut VM<'_>) -> RunResult { + let (a, b) = (&counts[self.index], &counts[other.index]); + if py_eq_item(a, b, vm)? { + Ok(self.rank > other.rank) + } else { + py_lt(a, b, vm) + } + } +} + +/// A port of CPython's `heapify` (`Modules/_heapqmodule.c`), including the cache-friendly order it uses above 2500 +/// entries, since the order of comparisons decides the result for counts that are not totally ordered. +fn heapify(heap: &mut [HeapEntry], counts: &[Value], vm: &mut VM<'_>) -> RunResult<()> { + let n = heap.len(); + if n > 2500 { + let m = n >> 1; // first childless node + let leftmost = keep_top_bit(m + 1) - 1; // leftmost node in the row of `m` + let mhalf = m >> 1; // parent of the first childless node + for i in (mhalf..leftmost).rev().chain((leftmost..m).rev()) { + let mut j = i; + loop { + sift_up(heap, j, counts, vm)?; + if j & 1 == 0 { + break; + } + j >>= 1; + } + } + } else { + for i in (0..n >> 1).rev() { + sift_up(heap, i, counts, vm)?; + } + } + Ok(()) +} + +/// `n` with every bit below its highest set bit cleared. +fn keep_top_bit(n: usize) -> usize { + if n == 0 { 0 } else { 1 << n.ilog2() } +} + +/// CPython's `siftup`: moves the smaller child up from `pos` until reaching a leaf, then sifts the entry that was +/// at `pos` back down into place. +fn sift_up(heap: &mut [HeapEntry], mut pos: usize, counts: &[Value], vm: &mut VM<'_>) -> RunResult<()> { + let start = pos; + let limit = heap.len() >> 1; + while pos < limit { + let mut child = 2 * pos + 1; + if child + 1 < heap.len() && !heap[child].lt(heap[child + 1], counts, vm)? { + child += 1; + } + heap.swap(child, pos); + pos = child; + } + sift_down(heap, start, pos, counts, vm) +} + +/// CPython's `siftdown`: moves the entry at `pos` towards `start` while it is less than its parent. +fn sift_down(heap: &mut [HeapEntry], start: usize, mut pos: usize, counts: &[Value], vm: &mut VM<'_>) -> RunResult<()> { + while pos > start { + let parent = (pos - 1) >> 1; + if !heap[pos].lt(heap[parent], counts, vm)? { + break; + } + heap.swap(pos, parent); + pos = parent; + } + Ok(()) +} + /// `Counter.elements()` — a list repeating each element by its count, skipping /// zero and negative counts (Monty's eager iterator convention returns a list /// rather than CPython's lazy iterator). diff --git a/crates/bashkit-monty/src/modules/collections/mod.rs b/crates/bashkit-monty/src/modules/collections/mod.rs index f3e7e93b6..e7d76b60c 100644 --- a/crates/bashkit-monty/src/modules/collections/mod.rs +++ b/crates/bashkit-monty/src/modules/collections/mod.rs @@ -34,7 +34,7 @@ use crate::{ heap::{DropWithContext, HeapData, HeapId, HeapReadOutput}, intern::StaticStrings, types::{ - Dict, Module, NamedTupleClass, PyTrait, Type, + BuiltinType, Dict, Module, NamedTupleClass, PyTrait, iter::collect_owned_iterable, str::{StringRepr, str_isidentifier}, }, @@ -46,7 +46,11 @@ use crate::{ pub fn create_module(vm: &mut VM<'_>) -> HeapId { let mut module = Module::new(StaticStrings::Collections, vm.interns); - module.set_attr(StaticStrings::Deque, Value::Builtin(Builtins::Type(Type::Deque)), vm); + module.set_attr( + StaticStrings::Deque, + Value::Builtin(Builtins::Type(BuiltinType::Deque)), + vm, + ); module.set_attr( StaticStrings::Namedtuple, Value::ModuleFunction(super::ModuleFunctions::Collections(CollectionsFunctions::Namedtuple)), @@ -56,12 +60,12 @@ pub fn create_module(vm: &mut VM<'_>) -> HeapId { // functions, so `type(d) is defaultdict` and `isinstance(c, Counter)` hold. module.set_attr( StaticStrings::Defaultdict, - Value::Builtin(Builtins::Type(Type::DefaultDict)), + Value::Builtin(Builtins::Type(BuiltinType::DefaultDict)), vm, ); module.set_attr( StaticStrings::Counter, - Value::Builtin(Builtins::Type(Type::Counter)), + Value::Builtin(Builtins::Type(BuiltinType::Counter)), vm, ); @@ -222,7 +226,7 @@ fn namedtuple(vm: &mut VM<'_>, args: ArgValues) -> RunResult { name } else { let as_str = typename.py_str(vm)?; - let owned = as_str.to_str(vm).map(str::to_owned); + let owned = as_str.try_to_str(vm).map(str::to_owned); as_str.drop_with(vm); EitherStr::from(owned?) }; @@ -278,7 +282,7 @@ fn parse_field_names(field_names: &Value, vm: &mut VM<'_>) -> RunResult) -> Copyability { // `operator.getitem`, see `limitations/copy.md`. | HeapReadOutput::GenericAlias(_) | HeapReadOutput::Union(_) + | HeapReadOutput::ForwardRef(_) | HeapReadOutput::FunctionDefaults(_) => Copyability::Shared, // Refused, with the `TypeError` CPython's pickler raises. Views and // iterators are positions into something else; the rest are host diff --git a/crates/bashkit-monty/src/modules/csv.rs b/crates/bashkit-monty/src/modules/csv.rs index 8ab8f3ff5..80c0a1ea1 100644 --- a/crates/bashkit-monty/src/modules/csv.rs +++ b/crates/bashkit-monty/src/modules/csv.rs @@ -23,7 +23,7 @@ use crate::{ modules::ModuleFunctions, os_dispatch::PostConversionEffect, types::{ - CsvObject, List, Module, PyTrait, Type, + BuiltinType, CsvObject, List, Module, PyTrait, Type, csv::{ DIALECT_NAMES, Dialect, DictReader, DictWriter, FIELD_SIZE_LIMIT, FmtParams, Quoting, Reader, Writer, write_method, @@ -64,9 +64,9 @@ pub fn create_module(vm: &mut VM<'_>) -> HeapId { module.set_attr(name, Value::ModuleFunction(ModuleFunctions::Csv(function)), vm); } for (name, type_) in [ - (StaticStrings::DictReader, Type::CsvDictReader), - (StaticStrings::DictWriter, Type::CsvDictWriter), - (StaticStrings::DialectClass, Type::CsvDialect), + (StaticStrings::DictReader, BuiltinType::CsvDictReader), + (StaticStrings::DictWriter, BuiltinType::CsvDictWriter), + (StaticStrings::DialectClass, BuiltinType::CsvDialect), ] { module.set_attr(name, Value::Builtin(Builtins::Type(type_)), vm); } @@ -119,7 +119,7 @@ fn call_reader(vm: &mut VM<'_>, args: ArgValues) -> RunResult { /// `csv.DictReader(f, ...)` as called from Python, loading an unread file first. pub(crate) fn dict_reader_call(vm: &mut VM<'_>, args: ArgValues) -> RunResult { - let callable = Value::Builtin(Builtins::Type(Type::CsvDictReader)); + let callable = Value::Builtin(Builtins::Type(BuiltinType::CsvDictReader)); match load_then_call(callable, args, Some("f"), vm) { Ok(load) => Ok(load), Err(args) => dict_reader_init(vm, args).map(CallResult::Value), @@ -246,11 +246,7 @@ fn call_writer(vm: &mut VM<'_>, args: ArgValues) -> RunResult { fn call_get_dialect(vm: &mut VM<'_>, args: ArgValues) -> RunResult { let GetDialectArgs { name } = GetDialectArgs::from_args(args, vm)?; defer_drop!(name, vm); - let dialect = if name.is_str(vm.heap) { - Dialect::by_name(name.to_str(vm)?) - } else { - None - }; + let dialect = name.as_str(vm).and_then(Dialect::by_name); dialect .map(|dialect| CsvObject::Dialect(dialect).allocate(vm)) .ok_or_else(ExcType::csv_unknown_dialect) @@ -480,10 +476,9 @@ fn materialize_fieldnames(fieldnames: &mut Value, vm: &mut VM<'_>) -> RunResult< /// `extrasaction.lower()`, which must be `'raise'` or `'ignore'` and is what gets stored. fn check_extrasaction(extrasaction: &Value, vm: &VM<'_>) -> RunResult { - if !extrasaction.is_str(vm.heap) { - return Err(ExcType::attribute_error(extrasaction.py_type_name(vm), "lower")); - } - let text = extrasaction.to_str(vm)?; + let text = extrasaction + .as_str(vm) + .ok_or_else(|| ExcType::attribute_error(extrasaction.py_type_name(vm), "lower"))?; let lowered = text.to_lowercase(); if lowered == "raise" || lowered == "ignore" { Ok(allocate_string(lowered, vm.heap)) diff --git a/crates/bashkit-monty/src/modules/dataclasses/method.rs b/crates/bashkit-monty/src/modules/dataclasses/method.rs index ad455c7d8..09386f843 100644 --- a/crates/bashkit-monty/src/modules/dataclasses/method.rs +++ b/crates/bashkit-monty/src/modules/dataclasses/method.rs @@ -419,7 +419,10 @@ pub(crate) fn frozen_assignment_error(class_id: HeapId, name: &Value, vm: &mut V fn frozen_field_error(action: &str, name: &Value, vm: &mut VM<'_>) -> RunResult { let name = name.py_repr(vm)?; defer_drop!(name, vm); - let message = format!("cannot {action} field {}", name.to_str(vm)?); + let message = format!( + "cannot {action} field {}", + name.as_str(vm).expect("py_repr returns str") + ); Ok(SimpleException::new_msg(ExcType::FrozenInstanceError, message).into()) } diff --git a/crates/bashkit-monty/src/modules/dataclasses/mod.rs b/crates/bashkit-monty/src/modules/dataclasses/mod.rs index 47edf7500..fdd98bdb6 100644 --- a/crates/bashkit-monty/src/modules/dataclasses/mod.rs +++ b/crates/bashkit-monty/src/modules/dataclasses/mod.rs @@ -34,9 +34,13 @@ use crate::{ exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, heap::{DropGuard, DropWithContext, Heap, HeapData, HeapId, HeapRead, HeapReadMut, HeapReadOutput, HeapReader}, intern::{Interns, StaticStrings, StringId}, - modules::ModuleFunctions, + modules::{ + ModuleFunctions, + typing::{self, HintFormat, HintsRequest, HintsTask}, + }, types::{ Class, Dict, Module, PyTrait, TupleVec, allocate_tuple, + generic_alias::AliasOrigin, host_class::host_class_type, instance::{class_defines, namespace_member}, }, @@ -248,15 +252,27 @@ struct ConfiguredArgs { fn apply_dataclass(vm: &mut VM<'_>, cls: Value, options: DataclassOptions) -> RunResult { let mut guard = DropGuard::new(cls, vm); let (cls, vm) = guard.as_parts(); + match cls { + Value::Ref(class_id) if matches!(vm.heap.get(*class_id), HeapData::Class(_)) => { + decorate_class(cls, *class_id, options, vm)?; + } + _ => return Err(non_class_error(cls, vm)), + } + Ok(guard.into_inner()) +} + +/// The decoration proper, for `cls` known to be the class `class_id` and kept +/// alive by the caller. +fn decorate_class(cls: &Value, class_id: HeapId, options: DataclassOptions, vm: &mut VM<'_>) -> RunResult<()> { + // Evaluated before the class is read: an annotation may refer to the class. + let annotations = dataclass_annotations(cls, vm)?; + defer_drop!(annotations, vm); // Read once and pass the handle down: everything below then works from a - // value already known to be a class, and the guard's reference keeps it alive. - let Value::Ref(class_id) = cls else { - return Err(non_class_error(cls, vm)); + // value already known to be a class. + let HeapReadOutput::Class(class) = vm.heap.read(class_id) else { + unreachable!("the caller checked the class") }; - let HeapReadOutput::Class(class) = vm.heap.read(*class_id) else { - return Err(non_class_error(cls, vm)); - }; - let fields = build_dataclass_fields(&class, vm)?; + let fields = build_dataclass_fields(&class, annotations, vm)?; let Value::Ref(fields_id) = fields else { unreachable!("the fields mapping is a dict") }; @@ -267,9 +283,8 @@ fn apply_dataclass(vm: &mut VM<'_>, cls: Value, options: DataclassOptions) -> Ru // as attributes can be rewritten to what CPython leaves behind. rewrite_field_attributes(&class, fields_id, vm)?; store_dataclass_params(&class, options, vm)?; - install_generated_methods(*class_id, &class, fields_id, options, &mut Installer::Decorate(vm))?; - store_match_args(&class, fields_id, vm)?; - Ok(guard.into_inner()) + install_generated_methods(class_id, &class, fields_id, options, &mut Installer::Decorate(vm))?; + store_match_args(&class, fields_id, vm) } /// `dataclass()` applied to something that is not a class. @@ -282,16 +297,34 @@ fn non_class_error(cls: &Value, vm: &VM<'_>) -> RunError { .into() } -/// Builds the `name -> Field` mapping for `class` from its `__annotations__`: -/// the annotated names in definition order, minus `ClassVar` entries, each -/// owning the default the class namespace bound for it (`y: int = 5`). +/// The class's annotations as CPython's decorator reads them, +/// `annotationlib.get_annotations(cls, format=Format.FORWARDREF)`: evaluated +/// where they were written, an unresolvable name left as a `ForwardRef`. +/// +/// Evaluation runs synchronously, in the same position as a `default_factory` +/// (see `limitations/dataclasses.md`); in `FORWARDREF` format it never asks the +/// host for a name. +fn dataclass_annotations(cls: &Value, vm: &mut VM<'_>) -> RunResult { + let request = HintsRequest { + format: HintFormat::ForwardRef, + globalns: None, + localns: None, + include_extras: true, + task: HintsTask::Annotations { eval_str: false }, + }; + typing::collect_hints(cls, &request, vm)?.require_synchronous(vm) +} + +/// Builds the `name -> Field` mapping for `class` from its evaluated +/// `annotations`: the annotated names in definition order, minus `ClassVar` +/// entries, each owning the default the class namespace bound for it (`y: int = 5`). /// /// Also where a class body Monty cannot yet honour is rejected, so an /// unimplemented feature raises rather than producing a subtly wrong class /// (see `limitations/dataclasses.md`). The fields are guarded throughout, so a /// rejection releases the defaults already captured. -fn build_dataclass_fields<'h>(class: &HeapRead<'h, Class>, vm: &mut VM<'h>) -> RunResult { - let fields = collect_annotated_fields(class, vm); +fn build_dataclass_fields<'h>(class: &HeapRead<'h, Class>, annotations: &Value, vm: &mut VM<'h>) -> RunResult { + let fields = collect_annotated_fields(class, annotations, vm); let mut guard = DropGuard::new(fields, vm); let (fields, vm) = guard.as_parts(); // Field validation runs first, so a class CPython would reject reports @@ -579,8 +612,8 @@ fn adopted_field_ids(fields_id: HeapId, heap: &Heap) -> Vec<(StringId, HeapId)> .collect() } -/// Collects the dataclass fields from `__annotations__`, in definition order, -/// dropping `ClassVar` entries, as owned references to heap `Field`s. +/// Collects the dataclass fields from the evaluated `annotations`, in definition +/// order, dropping `ClassVar` entries, as owned references to heap `Field`s. /// /// A class-body value that is already a `field()` result is **adopted in place** /// — the same object gains the name and annotation and goes on to @@ -590,8 +623,8 @@ fn adopted_field_ids(fields_id: HeapId, heap: &Heap) -> Vec<(StringId, HeapId)> /// /// The returned references are owned, so a caller that discards them must /// release them (`drop_with`). -fn collect_annotated_fields<'h>(class: &HeapRead<'h, Class>, vm: &mut VM<'h>) -> Vec { - let names = annotated_field_names(class, vm); +fn collect_annotated_fields<'h>(class: &HeapRead<'h, Class>, annotations: &Value, vm: &mut VM<'h>) -> Vec { + let names = annotated_field_names(annotations, vm); let mut guard = DropGuard::new(Vec::with_capacity(names.len()), vm); let (fields, vm) = guard.as_parts_mut(); for name_id in names { @@ -601,7 +634,7 @@ fn collect_annotated_fields<'h>(class: &HeapRead<'h, Class>, vm: &mut VM<'h>) -> let bound = namespace .get_by_str(vm.interns.get_str(name_id), vm.heap, vm.interns) .map(|v| v.clone_with_heap(vm.heap)); - let annotation = field_annotation(class, name_id, vm); + let annotation = field_annotation(annotations, name_id, vm); // The class body bound a `field()` result: it *is* the field, so it // takes the name and annotation and the list keeps that reference. // Anything else is a plain default, wrapped in a field of its own. @@ -624,50 +657,46 @@ fn collect_annotated_fields<'h>(class: &HeapRead<'h, Class>, vm: &mut VM<'h>) -> /// /// Names alone, so the collection loop can take the heap mutably instead of /// holding a borrow of the annotations dict across an allocation. -fn annotated_field_names<'h>(class: &HeapRead<'h, Class>, vm: &VM<'h>) -> Vec { - let Some(annotations) = annotations_dict(class, vm) else { - return Vec::new(); - }; - annotations - .into_iter() +fn annotated_field_names(annotations: &Value, vm: &VM<'_>) -> Vec { + annotations_dict(annotations, vm) + .iter() .filter_map(|(key, annotation)| match key { - Value::InternString(name_id) if !is_classvar(&annotation_text(annotation, vm)) => Some(*name_id), + Value::InternString(name_id) if !is_classvar(annotation, vm) => Some(*name_id), _ => None, }) .collect() } /// One field's annotation, cloned as an owned reference for the `Field` to hold. -fn field_annotation<'h>(class: &HeapRead<'h, Class>, name: StringId, vm: &VM<'h>) -> Value { - annotations_dict(class, vm) - .and_then(|annotations| annotations.get_by_str(vm.interns.get_str(name), vm.heap, vm.interns)) +fn field_annotation(annotations: &Value, name: StringId, vm: &VM<'_>) -> Value { + annotations_dict(annotations, vm) + .get_by_str(vm.interns.get_str(name), vm.heap, vm.interns) .map_or(Value::None, |annotation| annotation.clone_with_heap(vm.heap)) } -/// The class's `__annotations__` dict, or `None` for a class body with none. -fn annotations_dict<'a, 'h>(class: &HeapRead<'h, Class>, vm: &'a VM<'h>) -> Option<&'a Dict> { - match class - .get(vm.heap) - .namespace() - .get_by_str("__annotations__", vm.heap, vm.interns) - { - Some(Value::Ref(id)) => match vm.heap.get(*id) { - HeapData::Dict(annotations) => Some(annotations), - _ => None, - }, - _ => None, +/// The evaluated annotations as a dict (`get_annotations` always returns one). +fn annotations_dict<'a>(annotations: &Value, vm: &'a VM<'_>) -> &'a Dict { + let Value::Ref(id) = annotations else { + unreachable!("get_annotations returns a dict") + }; + let HeapData::Dict(dict) = vm.heap.get(*id) else { + unreachable!("get_annotations returns a dict") + }; + dict +} + +/// The text of a string or `ForwardRef` annotation, which CPython's decorator +/// also matches by name; `None` for an evaluated object. +fn annotation_text(annotation: &Value, vm: &VM<'_>) -> Option { + match annotation { + Value::Ref(id) if let HeapData::ForwardRef(forward_ref) = vm.heap.get(*id) => forward_ref + .arg() + .as_either_str(vm.heap) + .map(|s| s.into_string(vm.interns)), + _ => annotation.as_either_str(vm.heap).map(|s| s.into_string(vm.interns)), } } -/// A stringized annotation as text, or `""` for the non-string annotations -/// Monty never produces (it always stores annotations as source text). -fn annotation_text(annotation: &Value, vm: &VM<'_>) -> String { - annotation - .as_either_str(vm.heap) - .map(|s| s.as_str(vm.interns).to_owned()) - .unwrap_or_default() -} - /// Rejects field lists Monty cannot honour, in CPython's checking order. /// /// CPython validates defaults per field as it collects them, so a mutable @@ -675,12 +704,13 @@ fn annotation_text(annotation: &Value, vm: &VM<'_>) -> String { fn validate_fields(vm: &mut VM<'_>, fields: &[Value]) -> RunResult<()> { for field_value in fields { // Read out first: hashing a default needs the heap mutably. - let Some((name, annotation_text, default)) = read_field(field_value, vm) else { + let Some((name, annotation, default)) = read_field(field_value, vm) else { continue; }; + defer_drop!(annotation, vm); defer_drop!(default, vm); let name = vm.interns.get_str(name).to_owned(); - if is_initvar(&annotation_text) { + if annotation.as_ref().is_some_and(|annotation| is_initvar(annotation, vm)) { return Err(ExcType::not_implemented(format!( "dataclass() does not yet support InitVar (field {name}), which would become an ordinary field" )) @@ -710,13 +740,12 @@ fn validate_fields(vm: &mut VM<'_>, fields: &[Value]) -> RunResult<()> { /// A collected field's name, annotation text, and a **cloned** default — the /// three things validation needs, read before it takes the heap mutably. -fn read_field(field: &Value, vm: &VM<'_>) -> Option<(StringId, String, Option)> { +fn read_field(field: &Value, vm: &VM<'_>) -> Option<(StringId, Option, Option)> { let Value::Ref(id) = field else { return None }; let field = field_at_id(vm.heap, *id)?; - let annotation = field.annotation().map_or_else(String::new, |a| annotation_text(a, vm)); Some(( field.name().expect("collection adopts every field"), - annotation, + field.annotation().map(|a| a.clone_with_heap(vm.heap)), field.default().map(|d| d.clone_with_heap(vm.heap)), )) } @@ -743,20 +772,27 @@ fn first_non_default_after_default(fields: &[Value], vm: &VM<'_>) -> Option<(Str }) } -/// Whether a stringized annotation denotes `typing.ClassVar`, so the field is -/// excluded. +/// Whether an annotation denotes `typing.ClassVar`, so the field is excluded: +/// the form itself or its subscription, or a string / `ForwardRef` naming it, +/// the path CPython keeps for PEP 563 code. /// -/// Detection is textual where CPython resolves the annotation through the -/// defining module, so neither the import nor a dotted spelling's module is -/// checked — both divergences are in `limitations/dataclasses.md`. -fn is_classvar(annotation: &str) -> bool { - annotation_head(annotation, "ClassVar") +/// The textual match is where CPython resolves the name through the defining +/// module, so neither the import nor a dotted spelling's module is checked — +/// both divergences are in `limitations/dataclasses.md`. +fn is_classvar(annotation: &Value, vm: &VM<'_>) -> bool { + match annotation { + Value::Marker(Marker(StaticStrings::ClassVar)) => true, + Value::Ref(id) if let HeapData::GenericAlias(alias) = vm.heap.get(*id) => { + alias.origin() == AliasOrigin::Special(Marker(StaticStrings::ClassVar)) + } + _ => annotation_text(annotation, vm).is_some_and(|text| annotation_head(&text, "ClassVar")), + } } -/// Whether a stringized annotation denotes `dataclasses.InitVar`. Matched the -/// same way as [`is_classvar`], and with the same textual-only caveats. -fn is_initvar(annotation: &str) -> bool { - annotation_head(annotation, "InitVar") +/// Whether a string or `ForwardRef` annotation names `dataclasses.InitVar`, +/// which Monty has no object for; matched as [`is_classvar`] matches text. +fn is_initvar(annotation: &Value, vm: &VM<'_>) -> bool { + annotation_text(annotation, vm).is_some_and(|text| annotation_head(&text, "InitVar")) } /// Whether a stringized annotation names `name`, bare, subscripted, or diff --git a/crates/bashkit-monty/src/modules/datetime.rs b/crates/bashkit-monty/src/modules/datetime.rs index 597a7bc57..71c6c6e9a 100644 --- a/crates/bashkit-monty/src/modules/datetime.rs +++ b/crates/bashkit-monty/src/modules/datetime.rs @@ -15,7 +15,7 @@ use crate::{ bytecode::VM, heap::{HeapData, HeapId}, intern::StaticStrings, - types::{Module, Type}, + types::{BuiltinType, Module}, value::Value, }; @@ -24,21 +24,29 @@ use crate::{ pub fn create_module(vm: &mut VM<'_>) -> HeapId { let mut module = Module::new(StaticStrings::Datetime, vm.interns); - module.set_attr(StaticStrings::Date, Value::Builtin(Builtins::Type(Type::Date)), vm); + module.set_attr( + StaticStrings::Date, + Value::Builtin(Builtins::Type(BuiltinType::Date)), + vm, + ); module.set_attr( StaticStrings::Datetime, - Value::Builtin(Builtins::Type(Type::DateTime)), + Value::Builtin(Builtins::Type(BuiltinType::DateTime)), + vm, + ); + module.set_attr( + StaticStrings::Time, + Value::Builtin(Builtins::Type(BuiltinType::Time)), vm, ); - module.set_attr(StaticStrings::Time, Value::Builtin(Builtins::Type(Type::Time)), vm); module.set_attr( StaticStrings::Timedelta, - Value::Builtin(Builtins::Type(Type::TimeDelta)), + Value::Builtin(Builtins::Type(BuiltinType::TimeDelta)), vm, ); module.set_attr( StaticStrings::Timezone, - Value::Builtin(Builtins::Type(Type::TimeZone)), + Value::Builtin(Builtins::Type(BuiltinType::TimeZone)), vm, ); diff --git a/crates/bashkit-monty/src/modules/decimal.rs b/crates/bashkit-monty/src/modules/decimal.rs index 4dc013361..4403ee2c2 100644 --- a/crates/bashkit-monty/src/modules/decimal.rs +++ b/crates/bashkit-monty/src/modules/decimal.rs @@ -13,7 +13,7 @@ use crate::{ intern::StaticStrings, modules::ModuleFunctions, types::{ - Module, NamedTupleClass, Type, allocate_string, + BuiltinType, Module, NamedTupleClass, allocate_string, decimal::{ context::{MAX_EMAX, MAX_PREC, MIN_EMIN, MIN_ETINY, Rounding}, py_context::{self, IEEE_CONTEXT_MAX_BITS, Template}, @@ -70,12 +70,12 @@ pub fn create_module(vm: &mut VM<'_>) -> HeapId { let mut module = Module::new(StaticStrings::DecimalMod, vm.interns); module.set_attr( StaticStrings::DecimalType, - Value::Builtin(Builtins::Type(Type::Decimal)), + Value::Builtin(Builtins::Type(BuiltinType::Decimal)), vm, ); module.set_attr( StaticStrings::ContextType, - Value::Builtin(Builtins::Type(Type::DecimalContext)), + Value::Builtin(Builtins::Type(BuiltinType::DecimalContext)), vm, ); for (name, function) in [ diff --git a/crates/bashkit-monty/src/modules/fnmatch.rs b/crates/bashkit-monty/src/modules/fnmatch.rs new file mode 100644 index 000000000..30e72e821 --- /dev/null +++ b/crates/bashkit-monty/src/modules/fnmatch.rs @@ -0,0 +1,498 @@ +//! The `fnmatch` module: shell-style pattern matching. +//! +//! A pattern is compiled once per call into [`Token`]s by the algorithm of +//! CPython's `fnmatch.translate()`, so the odd corners of its character-class +//! handling (`[a--]` never matches, `[!b-a]` matches any character) carry over. +//! Names are matched against the tokens directly rather than through `re`; +//! `translate()` renders the same tokens as the regex text CPython 3.14 writes. +//! +//! The sandbox's `os.path` is `posixpath`, whose `normcase` is the identity, so +//! `fnmatch()` and `fnmatchcase()` differ only in how they convert their arguments. + +use monty_types::{ResourceError, ResourceTracker}; + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::{DropGuard, HeapData, HeapId}, + intern::StaticStrings, + modules::ModuleFunctions, + os_dispatch::{value_as_bytes, value_as_path_str}, + types::{List, Module, str::allocate_string}, + value::Value, +}; + +/// The module's four functions. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "snake_case")] +pub(crate) enum FnmatchFunctions { + Fnmatch, + Fnmatchcase, + Filter, + Translate, +} + +/// Creates the `fnmatch` module. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Fnmatch, vm.interns); + for (name, function) in [ + (StaticStrings::Fnmatch, FnmatchFunctions::Fnmatch), + (StaticStrings::Fnmatchcase, FnmatchFunctions::Fnmatchcase), + (StaticStrings::Filter, FnmatchFunctions::Filter), + (StaticStrings::Translate, FnmatchFunctions::Translate), + ] { + module.set_attr(name, Value::ModuleFunction(ModuleFunctions::Fnmatch(function)), vm); + } + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a call to one of the module's functions. +pub(super) fn call(vm: &mut VM<'_>, function: FnmatchFunctions, args: ArgValues) -> RunResult { + match function { + FnmatchFunctions::Fnmatch => { + let FnmatchArgs { name, pat } = FnmatchArgs::from_args(args, vm)?; + defer_drop!(name, vm); + defer_drop!(pat, vm); + // `normcase` runs `os.fspath` on both, so a `Path` is accepted and a bad type gets its wording. + let name = Text::from_path_like(name, vm)?; + let pat = Text::from_path_like(pat, vm)?; + Ok(Value::Bool(fnmatchcase(&name, &pat, &vm.heap.tracker)?)) + } + FnmatchFunctions::Fnmatchcase => { + let FnmatchcaseArgs { name, pat } = FnmatchcaseArgs::from_args(args, vm)?; + defer_drop!(name, vm); + defer_drop!(pat, vm); + // The pattern compiles first, then the subject gets `re`'s wording. + let pat = Text::from_pattern(pat, vm)?; + let name = Text::from_subject(name, vm)?; + Ok(Value::Bool(fnmatchcase(&name, &pat, &vm.heap.tracker)?)) + } + FnmatchFunctions::Filter => { + let FilterArgs { names, pat } = FilterArgs::from_args(args, vm)?; + filter(names, pat, vm) + } + FnmatchFunctions::Translate => { + let TranslateArgs { pat } = TranslateArgs::from_args(args, vm)?; + defer_drop!(pat, vm); + let pat = Text::from_pattern_str(pat, vm)?; + Ok(allocate_string(translate(&compile(&pat)), vm.heap)) + } + } +} + +/// Argument shape for `fnmatch(name, pat)`. +#[derive(FromArgs)] +#[from_args(name = "fnmatch", style = def)] +struct FnmatchArgs { + name: Value, + pat: Value, +} + +/// Argument shape for `fnmatchcase(name, pat)`. +#[derive(FromArgs)] +#[from_args(name = "fnmatchcase", style = def)] +struct FnmatchcaseArgs { + name: Value, + pat: Value, +} + +/// Argument shape for `filter(names, pat)`. +#[derive(FromArgs)] +#[from_args(name = "filter", style = def)] +struct FilterArgs { + names: Value, + pat: Value, +} + +/// Argument shape for `translate(pat)`. +#[derive(FromArgs)] +#[from_args(name = "translate", style = def)] +struct TranslateArgs { + pat: Value, +} + +/// `filter(names, pat)`: the members of `names` that match, in order and unchanged. +fn filter(names: Value, pat: Value, vm: &mut VM<'_>) -> RunResult { + // `names` is only consumed once the pattern binds, so a bad pattern wins over a bad iterable. + let mut names_guard = DropGuard::new(names, vm); + let (_, vm) = names_guard.as_parts_mut(); + let pat = { + defer_drop!(pat, vm); + Text::from_path_like(pat, vm)? + }; + let (names, vm) = names_guard.into_parts(); + let tokens = compile(&pat.chars); + let iter = names.into_py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(iter, vm); + let mut iter = iter.read(vm); + + let mut out_guard = DropGuard::new(Vec::new(), vm); + let (out, vm) = out_guard.as_parts_mut(); + let mut seen = 0; + while let Some(item) = iter.py_next(vm)? { + let mut item_guard = DropGuard::new(item, vm); + let (item, vm) = item_guard.as_parts_mut(); + // The source may yield without running bytecode, and every name is copied, + // so the drain polls the limits itself as `list()` does. + vm.heap.tracker.check_memory_time_every(seen)?; + seen += 1; + let name = Text::from_subject(item, vm)?; + if matches(&tokens, &pattern_subject(&name, &pat)?.chars, &vm.heap.tracker)? { + out.push(item_guard.into_inner()); + } + } + let (out, vm) = out_guard.into_parts(); + Ok(Value::Ref(vm.heap.allocate(HeapData::List(List::new(out))))) +} + +/// `fnmatchcase(name, pat)` on converted arguments. +fn fnmatchcase(name: &Text, pat: &Text, tracker: &ResourceTracker) -> RunResult { + let name = pattern_subject(name, pat)?; + Ok(matches(&compile(&pat.chars), &name.chars, tracker)?) +} + +/// Checks that `name` and `pat` are both `str` or both `bytes`, raising `re`'s +/// mixed-types errors otherwise, and lends `name` back. +fn pattern_subject<'a>(name: &'a Text, pat: &Text) -> RunResult<&'a Text> { + match (name.is_bytes, pat.is_bytes) { + (true, false) => Err(ExcType::type_error( + "cannot use a string pattern on a bytes-like object", + )), + (false, true) => Err(ExcType::type_error( + "cannot use a bytes pattern on a string-like object", + )), + _ => Ok(name), + } +} + +/// A `str` or `bytes` argument as code points: bytes are read as Latin-1, as +/// CPython's `fnmatch` decodes them, so one matcher serves both. +struct Text { + chars: Vec, + is_bytes: bool, +} + +impl Text { + /// `os.fspath(value)`: `str`, `bytes` or a path object, with `fspath`'s error. + fn from_path_like(value: &Value, vm: &VM<'_>) -> RunResult { + Self::extract(value, vm).ok_or_else(|| ExcType::type_error_fspath(&value.py_type_name(vm))) + } + + /// A subject handed straight to the compiled pattern: `str` or `bytes`, with + /// `re`'s error for anything else (a path object included). + fn from_subject(value: &Value, vm: &VM<'_>) -> RunResult { + Self::extract_text(value, vm).ok_or_else(|| { + ExcType::type_error(format!( + "expected string or bytes-like object, got '{}'", + value.py_type_name(vm) + )) + }) + } + + /// `fnmatchcase`'s pattern, which CPython reads with `len()` first: `str` or + /// `bytes`, else `object of type 'X' has no len()`. + fn from_pattern(value: &Value, vm: &VM<'_>) -> RunResult { + Self::extract_text(value, vm).ok_or_else(|| ExcType::type_error_no_len(&value.py_type_name(vm))) + } + + /// `translate`'s pattern, which must be `str`: CPython indexes a `bytes` + /// pattern into ints and fails decoding the first one. + fn from_pattern_str(value: &Value, vm: &VM<'_>) -> RunResult> { + let text = Self::from_pattern(value, vm)?; + if text.is_bytes && !text.chars.is_empty() { + Err(ExcType::type_error( + "decoding to str: need a bytes-like object, int found", + )) + } else { + Ok(text.chars) + } + } + + /// `str`, `bytes` or path-like text, else `None`. + fn extract(value: &Value, vm: &VM<'_>) -> Option { + value_as_path_str(value, vm.heap, vm.interns) + .map(Self::str) + .or_else(|| value_as_bytes(value, vm.heap, vm.interns).map(Self::bytes)) + } + + /// `str` or `bytes` text only, else `None`. + fn extract_text(value: &Value, vm: &VM<'_>) -> Option { + if value.is_str(vm.heap) { + value_as_path_str(value, vm.heap, vm.interns).map(Self::str) + } else { + value_as_bytes(value, vm.heap, vm.interns).map(Self::bytes) + } + } + + fn str(text: &str) -> Self { + Self { + chars: text.chars().collect(), + is_bytes: false, + } + } + + fn bytes(bytes: &[u8]) -> Self { + Self { + chars: bytes.iter().map(|&byte| char::from(byte)).collect(), + is_bytes: true, + } + } +} + +/// One element of a compiled pattern; `translate()` renders each the way +/// CPython's `_translate` does. +#[derive(Debug, PartialEq, Eq)] +enum Token { + /// A character matched verbatim. + Literal(char), + /// `?`: any single character, newline included. + AnyChar, + /// `*`: any run of characters; consecutive stars collapse into one. + Star, + /// `[...]` that CPython reduces to an empty range, which never matches. + Never, + /// `[...]` whose members CPython reduces to `!` alone, matching any character. + NegatedEmpty, + /// A character class. + Class(Class), +} + +/// The members of a `[...]` class and the text CPython writes for it. +#[derive(Debug, PartialEq, Eq)] +struct Class { + negated: bool, + chars: Vec, + /// Inclusive ranges, `lo <= hi`. + ranges: Vec<(char, char)>, + /// The regex body between the brackets, `^` prefix included. + rendered: String, +} + +impl Class { + /// Whether `c` is a member, negation applied. + fn contains(&self, c: char) -> bool { + let member = self.chars.contains(&c) || self.ranges.iter().any(|&(lo, hi)| (lo..=hi).contains(&c)); + member != self.negated + } +} + +/// Compiles a pattern by CPython's `_translate` algorithm. +fn compile(pat: &[char]) -> Vec { + let n = pat.len(); + let mut tokens = Vec::new(); + let mut i = 0; + while i < n { + let c = pat[i]; + i += 1; + match c { + '*' => { + if tokens.last() != Some(&Token::Star) { + tokens.push(Token::Star); + } + } + '?' => tokens.push(Token::AnyChar), + '[' => { + // Find the closing bracket: a leading `!` and a leading `]` are members. + let mut j = i; + if j < n && pat[j] == '!' { + j += 1; + } + if j < n && pat[j] == ']' { + j += 1; + } + while j < n && pat[j] != ']' { + j += 1; + } + if j >= n { + tokens.push(Token::Literal('[')); + } else { + tokens.push(compile_class(&pat[i..j])); + i = j + 1; + } + } + c => tokens.push(Token::Literal(c)), + } + } + tokens +} + +/// Compiles the text between `[` and `]`. +/// +/// CPython splits the text at the hyphens that form ranges (`chunks`), drops +/// ranges whose bounds are reversed by merging the chunks around them, then +/// escapes what remains; the members and the rendered text come from the same chunks. +fn compile_class(stuff: &[char]) -> Token { + let negated = stuff.first() == Some(&'!'); + let chunks = if stuff.contains(&'-') { + let mut chunks: Vec> = Vec::new(); + let mut start = 0; + // The hyphen right after `[` or `[!` is a member, not a range. + let mut k = if negated { 2 } else { 1 }; + while let Some(offset) = stuff[k.min(stuff.len())..].iter().position(|&c| c == '-') { + k += offset; + chunks.push(stuff[start..k].to_vec()); + start = k + 1; + // Skip the range's end character, and the one after it: a hyphen there is a member. + k += 3; + } + if start < stuff.len() { + chunks.push(stuff[start..].to_vec()); + } else { + // A trailing hyphen closes no range and is a member. + chunks.last_mut().expect("a hyphen was found").push('-'); + } + // Remove reversed ranges, which a regex rejects, by merging their chunks. + let mut k = chunks.len() - 1; + while k > 0 { + let lo = *chunks[k - 1].last().expect("chunks are never empty before merging"); + let hi = chunks[k][0]; + if lo > hi { + let tail: Vec = chunks[k][1..].to_vec(); + let merged = &mut chunks[k - 1]; + merged.pop(); + merged.extend(tail); + chunks.remove(k); + } + k -= 1; + } + chunks + } else { + vec![stuff.to_vec()] + }; + + let mut chars = Vec::new(); + let mut ranges = Vec::new(); + let mut rendered = String::new(); + for (k, chunk) in chunks.iter().enumerate() { + let mut members = &chunk[..]; + if k > 0 { + // The first character ends the range the previous chunk started. + let hi = chunk[0]; + let lo = chars.pop().expect("a range start was recorded"); + ranges.push((lo, hi)); + members = &members[1..]; + rendered.push('-'); + } + if k == 0 && negated { + members = &members[1..]; + } + chars.extend_from_slice(members); + for &c in chunk { + // Backslashes, hyphens and set operators are escaped; everything else is verbatim. + if matches!(c, '\\' | '-' | '&' | '~' | '|') { + rendered.push('\\'); + } + rendered.push(c); + } + } + + if rendered.is_empty() { + Token::Never + } else if rendered == "!" { + Token::NegatedEmpty + } else { + if negated { + rendered.replace_range(0..1, "^"); + } else if rendered.starts_with(['^', '[']) { + rendered.insert(0, '\\'); + } + Token::Class(Class { + negated, + chars, + ranges, + rendered, + }) + } +} + +/// Whether the whole of `text` matches `tokens`: a backtracking wildcard match +/// that is linear in the common case, remembering only the latest star. +fn matches(tokens: &[Token], text: &[char], tracker: &ResourceTracker) -> Result { + let (mut t, mut s) = (0, 0); + let mut star: Option<(usize, usize)> = None; + // Backtracking makes this quadratic in the worst case, so the clock is polled. + let mut steps = 0; + while s < text.len() { + tracker.check_time_every(steps)?; + steps += 1; + match tokens.get(t) { + Some(Token::Star) => { + star = Some((t, s)); + t += 1; + } + Some(token) if token_matches(token, text[s]) => { + t += 1; + s += 1; + } + _ => match star { + // Let the latest star absorb one more character and retry after it. + Some((star_t, star_s)) => { + t = star_t + 1; + s = star_s + 1; + star = Some((star_t, star_s + 1)); + } + None => return Ok(false), + }, + } + } + Ok(tokens[t..].iter().all(|token| *token == Token::Star)) +} + +/// Whether a single-character token matches `c`. +fn token_matches(token: &Token, c: char) -> bool { + match token { + Token::Literal(literal) => *literal == c, + Token::AnyChar | Token::NegatedEmpty => true, + Token::Never => false, + Token::Class(class) => class.contains(c), + Token::Star => unreachable!("stars are handled by the matcher"), + } +} + +/// Renders `tokens` as CPython's `translate()` does: an interior `*` before +/// fixed text becomes an atomic lazy group, the last one a greedy `.*`. +fn translate(tokens: &[Token]) -> String { + let mut out = String::from("(?s:"); + let mut parts = tokens.split(|token| *token == Token::Star); + if let Some(leading) = parts.next() { + render_fixed(&mut out, leading); + } + let mut parts = parts.peekable(); + while let Some(fixed) = parts.next() { + if parts.peek().is_none() { + out.push_str(".*"); + render_fixed(&mut out, fixed); + } else { + out.push_str("(?>.*?"); + render_fixed(&mut out, fixed); + out.push(')'); + } + } + out.push_str(")\\z"); + out +} + +/// Renders a run of tokens without stars. +fn render_fixed(out: &mut String, tokens: &[Token]) { + for token in tokens { + match token { + Token::Literal(c) => { + // `re.escape` escapes the regex metacharacters and ASCII whitespace. + if "()[]{}?*+-|^$\\.&~# \t\n\r\u{b}\u{c}".contains(*c) { + out.push('\\'); + } + out.push(*c); + } + Token::AnyChar | Token::NegatedEmpty => out.push('.'), + Token::Never => out.push_str("(?!)"), + Token::Class(class) => { + out.push('['); + out.push_str(&class.rendered); + out.push(']'); + } + Token::Star => unreachable!("stars are split off by translate"), + } + } +} diff --git a/crates/bashkit-monty/src/modules/functools.rs b/crates/bashkit-monty/src/modules/functools.rs index b6f5bdafe..2cd091793 100644 --- a/crates/bashkit-monty/src/modules/functools.rs +++ b/crates/bashkit-monty/src/modules/functools.rs @@ -15,7 +15,7 @@ use crate::{ heap::{HeapData, HeapId}, intern::StaticStrings, modules::ModuleFunctions, - types::{Module, PyTrait, Type, lru_cache}, + types::{BuiltinType, Module, PyTrait, lru_cache}, value::Value, }; @@ -25,12 +25,12 @@ def __monty_functools_reduce(function, iterable, accumulator, has_initial, iter_ try: iterator = iter_(iterable) except type_error: - raise type_error('reduce() arg 2 must support iteration') from None + raise type_error('reduce() arg 2 must support iteration') if not has_initial: try: accumulator = next_(iterator) except stop_iteration: - raise type_error('reduce() of empty iterable with no initial value') from None + raise type_error('reduce() of empty iterable with no initial value') while True: try: item = next_(iterator) @@ -62,7 +62,7 @@ pub fn create_module(vm: &mut VM<'_>) -> HeapId { ); module.set_attr( StaticStrings::Partial, - Value::Builtin(Builtins::Type(Type::Partial)), + Value::Builtin(Builtins::Type(BuiltinType::Partial)), vm, ); @@ -125,7 +125,7 @@ fn call_reduce(vm: &mut VM<'_>, args: ArgValues) -> RunResult { iterable, initial.unwrap_or(Value::None), Value::Bool(has_initial), - Value::Builtin(Builtins::Type(Type::Iterator)), + Value::Builtin(Builtins::Type(BuiltinType::Iterator)), Value::Builtin(Builtins::Function(BuiltinsFunctions::Next)), Value::Builtin(Builtins::ExcType(ExcType::StopIteration)), Value::Builtin(Builtins::ExcType(ExcType::TypeError)), diff --git a/crates/bashkit-monty/src/modules/hashlib.rs b/crates/bashkit-monty/src/modules/hashlib.rs index bc3df891b..483fcd791 100644 --- a/crates/bashkit-monty/src/modules/hashlib.rs +++ b/crates/bashkit-monty/src/modules/hashlib.rs @@ -27,7 +27,7 @@ use crate::{ intern::StaticStrings, modules::ModuleFunctions, types::{ - Module, Set, Type, allocate_string, + BuiltinType, Module, Set, allocate_string, bytes::allocate_bytes, hashlib::{Blake2Params, Blake2b, Blake2s, DigestBytes, HashAlgorithm, HashObject, hash_input}, }, @@ -86,12 +86,12 @@ pub fn create_module(vm: &mut VM<'_>) -> HeapId { } module.set_attr( StaticStrings::Blake2b, - Value::Builtin(Builtins::Type(Type::Blake2b)), + Value::Builtin(Builtins::Type(BuiltinType::Blake2b)), vm, ); module.set_attr( StaticStrings::Blake2s, - Value::Builtin(Builtins::Type(Type::Blake2s)), + Value::Builtin(Builtins::Type(BuiltinType::Blake2s)), vm, ); // Two sets, as in CPython, where mutating one leaves the other alone. @@ -209,7 +209,8 @@ fn construct(algorithm: HashAlgorithm, args: ConstructorArgs, vm: &mut VM<'_>) - defer_drop!(args, vm); let mut hash = HashObject::new(algorithm); if let Some(input) = initial_data(args.data.as_ref(), args.string.as_ref())? { - hash.update(hash_input(input, vm)?, &vm.heap.tracker)?; + let input = input.py_value(vm); + hash.update(hash_input(&input, vm)?, &vm.heap.tracker)?; } Ok(hash.allocate(vm.heap)) } @@ -260,7 +261,7 @@ struct OpensslNewArgs { /// OpenSSL alias such as `'blake2b512'` takes the plain path, as in CPython. fn call_new(vm: &mut VM<'_>, args: ArgValues) -> RunResult { let HashNewArgs { name, args, kwargs } = HashNewArgs::from_args(args, vm)?; - let blake2 = name.to_str(vm).ok().and_then(Blake2Kind::from_name); + let blake2 = name.as_str(vm).and_then(Blake2Kind::from_name); if let Some(kind) = blake2 { name.drop_with(vm); return blake2_init(kind, vm, ArgValues::from_parts(args, kwargs)); @@ -280,13 +281,12 @@ fn call_new(vm: &mut VM<'_>, args: ArgValues) -> RunResult { defer_drop!(usedforsecurity, vm); defer_drop!(string, vm); // The data is checked before the name is resolved, as `_hashlib.new` does. - let input = initial_data(data.as_ref(), string.as_ref())? - .map(|input| hash_input(input, vm)) - .transpose()?; + let input = initial_data(data.as_ref(), string.as_ref())?.map(|input| input.py_value(vm)); + let input_bytes = input.as_ref().map(|input| hash_input(input, vm)).transpose()?; let name = name.as_str(vm); let algorithm = HashAlgorithm::from_name(name).ok_or_else(|| unsupported_hash_type(name))?; let mut hash = HashObject::new(algorithm); - if let Some(input) = input { + if let Some(input) = input_bytes { hash.update(input, &vm.heap.tracker)?; } Ok(hash.allocate(vm.heap)) @@ -541,7 +541,8 @@ pub(crate) fn blake2_init(kind: Blake2Kind, vm: &mut VM<'_>, args: ArgValues) -> "maximum key length is {max_digest} bytes" ))); } - let input = input.map(|input| hash_input(input, vm)).transpose()?; + let py_input = input.map(|input| input.py_value(vm)); + let input = py_input.as_ref().map(|input| hash_input(input, vm)).transpose()?; let params = Blake2Params { digest_size, diff --git a/crates/bashkit-monty/src/modules/itertools.rs b/crates/bashkit-monty/src/modules/itertools.rs index a26ac14ef..b7da9095c 100644 --- a/crates/bashkit-monty/src/modules/itertools.rs +++ b/crates/bashkit-monty/src/modules/itertools.rs @@ -18,7 +18,7 @@ use crate::{ modules::ModuleFunctions, resource_checks::check_estimated_size, types::{ - ItertoolsIter, Module, TupleVec, Type, allocate_tuple, + BuiltinType, ItertoolsIter, Module, TupleVec, Type, allocate_tuple, iter::collect_owned_iterable, itertools::{ Accumulate, Batched, Chain, Combinations, Compress, Count, Cycle, DropWhile, FilterFalse, GroupBy, Islice, @@ -45,32 +45,32 @@ pub(crate) enum ItertoolsFunctions { } /// The module's type objects, by the name each is bound to. -const ITERTOOLS_TYPES: &[(StaticStrings, Type)] = &[ - (StaticStrings::Count, Type::ItertoolsCount), - (StaticStrings::Repeat, Type::ItertoolsRepeat), - (StaticStrings::Pairwise, Type::ItertoolsPairwise), - (StaticStrings::Compress, Type::ItertoolsCompress), - (StaticStrings::Islice, Type::ItertoolsIslice), - (StaticStrings::Chain, Type::ItertoolsChain), - (StaticStrings::Cycle, Type::ItertoolsCycle), - (StaticStrings::Takewhile, Type::ItertoolsTakeWhile), - (StaticStrings::Dropwhile, Type::ItertoolsDropWhile), - (StaticStrings::Filterfalse, Type::ItertoolsFilterFalse), - (StaticStrings::Starmap, Type::ItertoolsStarMap), - (StaticStrings::Accumulate, Type::ItertoolsAccumulate), - (StaticStrings::Batched, Type::ItertoolsBatched), - (StaticStrings::ZipLongest, Type::ItertoolsZipLongest), - (StaticStrings::Combinations, Type::ItertoolsCombinations), +const ITERTOOLS_TYPES: &[(StaticStrings, BuiltinType)] = &[ + (StaticStrings::Count, BuiltinType::ItertoolsCount), + (StaticStrings::Repeat, BuiltinType::ItertoolsRepeat), + (StaticStrings::Pairwise, BuiltinType::ItertoolsPairwise), + (StaticStrings::Compress, BuiltinType::ItertoolsCompress), + (StaticStrings::Islice, BuiltinType::ItertoolsIslice), + (StaticStrings::Chain, BuiltinType::ItertoolsChain), + (StaticStrings::Cycle, BuiltinType::ItertoolsCycle), + (StaticStrings::Takewhile, BuiltinType::ItertoolsTakeWhile), + (StaticStrings::Dropwhile, BuiltinType::ItertoolsDropWhile), + (StaticStrings::Filterfalse, BuiltinType::ItertoolsFilterFalse), + (StaticStrings::Starmap, BuiltinType::ItertoolsStarMap), + (StaticStrings::Accumulate, BuiltinType::ItertoolsAccumulate), + (StaticStrings::Batched, BuiltinType::ItertoolsBatched), + (StaticStrings::ZipLongest, BuiltinType::ItertoolsZipLongest), + (StaticStrings::Combinations, BuiltinType::ItertoolsCombinations), ( StaticStrings::CombinationsWithReplacement, - Type::ItertoolsCombinationsWithReplacement, + BuiltinType::ItertoolsCombinationsWithReplacement, ), - (StaticStrings::Permutations, Type::ItertoolsPermutations), - (StaticStrings::Product, Type::ItertoolsProduct), - (StaticStrings::Groupby, Type::ItertoolsGroupBy), - (StaticStrings::Grouper, Type::ItertoolsGrouper), - (StaticStrings::TeeType, Type::ItertoolsTee), - (StaticStrings::TeeDataObject, Type::ItertoolsTeeDataObject), + (StaticStrings::Permutations, BuiltinType::ItertoolsPermutations), + (StaticStrings::Product, BuiltinType::ItertoolsProduct), + (StaticStrings::Groupby, BuiltinType::ItertoolsGroupBy), + (StaticStrings::Grouper, BuiltinType::ItertoolsGrouper), + (StaticStrings::TeeType, BuiltinType::ItertoolsTee), + (StaticStrings::TeeDataObject, BuiltinType::ItertoolsTeeDataObject), ]; /// Creates the `itertools` module on the heap. diff --git a/crates/bashkit-monty/src/modules/json/dump.rs b/crates/bashkit-monty/src/modules/json/dump.rs index 774aae126..e9ba908d0 100644 --- a/crates/bashkit-monty/src/modules/json/dump.rs +++ b/crates/bashkit-monty/src/modules/json/dump.rs @@ -150,6 +150,8 @@ struct EncoderKwargs { allow_nan: Value, separators: Value, skipkeys: Value, + /// The `default` callable, or `None`; it is called, never validated, as in CPython. + default_fn: Value, } impl DropWithContext for EncoderKwargs { @@ -160,6 +162,7 @@ impl DropWithContext for EncoderKwargs { self.allow_nan.drop_with(ctx); self.separators.drop_with(ctx); self.skipkeys.drop_with(ctx); + self.default_fn.drop_with(ctx); } } @@ -167,10 +170,10 @@ impl DropWithContext for EncoderKwargs { /// /// Only the first argument may be positional. Supported keyword arguments mirror /// the high-value subset of CPython's encoder configuration: `indent`, -/// `sort_keys`, `ensure_ascii`, `allow_nan`, `separators`, and `skipkeys`. +/// `sort_keys`, `ensure_ascii`, `allow_nan`, `separators`, `skipkeys` and `default`. /// -/// CPython kwargs `cls`, `default`, and `check_circular` are intentionally -/// unsupported and will raise `TypeError` if passed. +/// CPython kwargs `cls` and `check_circular` are intentionally unsupported and +/// will raise `TypeError` if passed. pub(super) fn call_dumps(vm: &mut VM<'_>, args: ArgValues) -> RunResult { let JsonDumpsArgs { obj, @@ -180,6 +183,7 @@ pub(super) fn call_dumps(vm: &mut VM<'_>, args: ArgValues) -> RunResult { allow_nan, separators, skipkeys, + default_fn, } = JsonDumpsArgs::from_args(args, vm)?; // `obj` outlives kwarg processing: an early error below must not leak it. defer_drop!(obj, vm); @@ -190,10 +194,11 @@ pub(super) fn call_dumps(vm: &mut VM<'_>, args: ArgValues) -> RunResult { allow_nan, separators, skipkeys, + default_fn, }; defer_drop!(kwargs, vm); let config = JsonDumpsConfig::from_kwargs(kwargs, EncoderChecks::for_call(obj, false, vm), vm)?; - let output = encode(obj, &config, vm)?; + let output = encode(obj, &config, &kwargs.default_fn, vm)?; Ok(allocate_string(output, vm.heap)) } @@ -216,6 +221,7 @@ pub(super) fn call_dump(vm: &mut VM<'_>, args: ArgValues) -> RunResult, args: ArgValues) -> RunResult, args: ArgValues) -> RunResult target, @@ -246,13 +253,15 @@ pub(super) fn call_dump(vm: &mut VM<'_>, args: ArgValues) -> RunResult) -> RunResult { +/// Serializes `obj` to JSON text under `config`, calling `default` (when not +/// `None`) for values no JSON type covers. +fn encode(obj: &Value, config: &JsonDumpsConfig, default: &Value, vm: &mut VM<'_>) -> RunResult { let mut output = String::new(); let mut active_containers = Vec::new(); let mut encoder = Encoder { out: &mut output, config, + default, active_containers: &mut active_containers, vm, }; @@ -273,7 +282,7 @@ fn is_container(value: &Value, vm: &VM<'_>) -> bool { } /// Argument shape for `json.dumps(obj, *, indent=None, sort_keys=False, -/// ensure_ascii=True, allow_nan=True, separators=None, skipkeys=False)`. +/// ensure_ascii=True, allow_nan=True, separators=None, skipkeys=False, default=None)`. /// /// Arity and missing-arg errors use the `dumps()` descriptor with `style = /// def` wording (CPython's `json.dumps` is a pure-Python `def`), but the @@ -300,6 +309,8 @@ struct JsonDumpsArgs { separators: Value, #[from_args(kw_only, default = Value::Bool(false))] skipkeys: Value, + #[from_args(kw_only, static_string = "Default", default = Value::None)] + default_fn: Value, } /// Argument shape for `json.dump(obj, fp, *, …)`: [`JsonDumpsArgs`] with the @@ -321,6 +332,8 @@ struct JsonDumpArgs { separators: Value, #[from_args(kw_only, default = Value::Bool(false))] skipkeys: Value, + #[from_args(kw_only, static_string = "Default", default = Value::None)] + default_fn: Value, } /// Sets `bit` in `flags` when `value` is truthy, clearing it otherwise. Used by the json.dumps kwarg pipeline so each @@ -427,30 +440,22 @@ fn check_separators_length(len: usize) -> RunResult<()> { /// 5 for `key_separator`) so the error message matches CPython exactly. fn json_separator_to_string(value: &Value, role: &str, vm: &VM<'_>) -> RunResult { let arg_num = if role == "item_separator" { 6 } else { 5 }; - match value { - Value::InternString(string_id) => Ok(vm.interns.get_str(*string_id).to_owned()), - Value::Ref(heap_id) => match vm.heap.get(*heap_id) { - HeapData::Str(string) => Ok(string.as_str().to_owned()), - _ => Err(ExcType::type_error(format!( - "make_encoder() argument {arg_num} must be str, not {}", - value.py_type_name(vm) - ))), - }, - _ => Err(ExcType::type_error(format!( + value.try_to_str(vm).map(str::to_owned).map_err(|_| { + ExcType::type_error(format!( "make_encoder() argument {arg_num} must be str, not {}", value.py_type_name(vm) - ))), - } + )) + }) } /// Mutable serialization context shared across the recursive `serialize_*` /// methods. /// -/// Groups the four pieces of per-call state that every recursive level needs -/// — the JSON output buffer, the encoder configuration, the cycle-detection -/// stack, and the VM (heap + interns) — so the recursive methods can be -/// invoked as `encoder.serialize_value(value, depth)` rather than threading -/// five separate parameters through every signature. +/// Groups the per-call state that every recursive level needs — the JSON output +/// buffer, the encoder configuration, the `default` callable, the cycle-detection +/// stack, and the VM (heap + interns) — so the recursive methods can be invoked +/// as `encoder.serialize_value(value, depth)` rather than threading six separate +/// parameters through every signature. /// /// `depth` is intentionally **not** a field of this struct: every recursive /// call needs to bump it by one for the descent and restore it on return, @@ -458,6 +463,8 @@ fn json_separator_to_string(value: &Value, role: &str, vm: &VM<'_>) -> RunResult struct Encoder<'a, 'h> { out: &'a mut String, config: &'a JsonDumpsConfig, + /// The `default=` callable, or `None` when unserializable values raise. + default: &'a Value, active_containers: &'a mut Vec, vm: &'a mut VM<'h>, } @@ -555,20 +562,36 @@ impl<'h> Encoder<'_, 'h> { defer_drop!(token, this); this.with_entered_container(dict.id(), |enc| enc.serialize_dict(entries, depth)) } - _ => { - // CPython names the class by `__name__`: `Decimal`, not `decimal.Decimal`. - // A user class's name is its `__name__` already, dots and all. - let type_name = value.py_type_name(self.vm); - let bare = if matches!(value.py_type(self.vm), Type::Instance(_)) { - &*type_name - } else { - type_name.rsplit_once('.').map_or(&*type_name, |(_, bare)| bare) - }; - Err(ExcType::json_not_serializable_error(bare)) - } + _ => self.serialize_fallback(value, depth), + } + } + + /// Encodes a value no JSON type covers through `default(value)`, or raises + /// CPython's `TypeError` when no `default` was given. The value is marked + /// before `default` runs and stays marked while its replacement encodes, so a + /// revisit raises `Circular reference detected` without calling `default` again. + fn serialize_fallback(&mut self, value: &Value, depth: usize) -> RunResult<()> { + match (self.default, value) { + (Value::None, _) => Err(not_serializable(value, self.vm)), + (_, Value::Ref(id)) => self.with_entered_container(*id, |enc| enc.serialize_default(value, depth)), + // Immediates (a builtin function, say) have no heap identity to mark. + _ => self.serialize_default(value, depth), } } + /// Calls `default(value)` and encodes what it returns. + fn serialize_default(&mut self, value: &Value, depth: usize) -> RunResult<()> { + let argument = value.clone_with_heap(self.vm); + let replacement = self.vm.evaluate_function(self.default, ArgValues::One(argument))?; + let this = self; + defer_drop!(replacement, this); + // A `default` that keeps returning fresh unserializable values recurses + // without ever repeating a container, so the recursion limit bounds it. + let token = this.vm.recursion_token()?; + defer_drop!(token, this); + this.serialize_value(replacement, depth) + } + /// Streams items from a list or tuple into a JSON array, formatting /// separators and indentation between calls to `write_next`. /// @@ -752,6 +775,19 @@ impl<'h> Encoder<'_, 'h> { } } +/// CPython's `Object of type X is not JSON serializable`, naming the class by +/// `__name__`: `Decimal`, not `decimal.Decimal`. A user class's name is its +/// `__name__` already, dots and all. +fn not_serializable(value: &Value, vm: &VM<'_>) -> RunError { + let type_name = value.py_type_name(vm); + let bare = if matches!(value.py_type(vm), Type::Instance(_)) { + &*type_name + } else { + type_name.rsplit_once('.').map_or(&*type_name, |(_, bare)| bare) + }; + ExcType::json_not_serializable_error(bare) +} + /// Sorts dict entries in-place using Python comparison semantics on the keys. /// /// The implementation mirrors the error style used by `sorted()` and diff --git a/crates/bashkit-monty/src/modules/json/load.rs b/crates/bashkit-monty/src/modules/json/load.rs index 7f233062c..839d0d9b9 100644 --- a/crates/bashkit-monty/src/modules/json/load.rs +++ b/crates/bashkit-monty/src/modules/json/load.rs @@ -165,6 +165,7 @@ struct JsonLoadArgs { fn parse_json_input(value: &Value, hooks: &NumberHooks<'_>, vm: &mut VM<'_>) -> RunResult { let (bytes, is_str): (Cow<'_, [u8]>, bool) = match value { Value::InternString(string_id) => (Cow::Borrowed(vm.interns.get_str(*string_id).as_bytes()), true), + Value::InlineString(text) => (Cow::Borrowed(text.as_str().as_bytes()), true), Value::InternBytes(bytes_id) => (Cow::Borrowed(vm.interns.get_bytes(*bytes_id)), false), Value::Ref(heap_id) => match vm.heap.get(*heap_id) { HeapData::Str(s) => (Cow::Owned(s.as_str().as_bytes().to_vec()), true), @@ -264,12 +265,10 @@ fn parse_json_value_from_peek( } } -/// Allocates a string using the cache when eligible, falling back to direct -/// allocation for empty/single-char strings (already interned by -/// `allocate_string`). +/// Caches strings of 16–64 UTF-8 bytes and allocates other strings directly. fn allocate_cached_string(s: String, cache: &mut JsonStringCache, heap: &HeapReader<'_>) -> Value { - if s.len() < 2 { - // Empty and single-char strings are interned by allocate_string. + if s.len() <= 15 { + // Empty and single-char strings are interned; 2–15 byte strings are inline. allocate_string(s, heap.heap()) } else { cache.get_or_allocate(s, heap) diff --git a/crates/bashkit-monty/src/modules/json/string_cache.rs b/crates/bashkit-monty/src/modules/json/string_cache.rs index b349b2b2b..ba199ad7a 100644 --- a/crates/bashkit-monty/src/modules/json/string_cache.rs +++ b/crates/bashkit-monty/src/modules/json/string_cache.rs @@ -1,10 +1,8 @@ //! Per-run string cache for `json.loads()`. //! -//! Repeated JSON parsing within a single execution often encounters the same -//! strings — especially dict keys like `"id"`, `"name"`, `"type"` — across -//! multiple `json.loads()` calls. This cache deduplicates heap allocations for -//! those strings by hashing incoming bytes and returning a `clone_with_heap` of -//! a previously allocated `Value` on cache hits. +//! This cache deduplicates repeated strings of 16–64 UTF-8 bytes across +//! `json.loads()` calls within one execution. Shorter strings are interned or +//! stored inline. Cache hits return a `clone_with_heap` of the existing `Value`. //! //! The design is modelled on jiter's `PyStringCache`: a fixed-capacity //! fully-associative cache with linear probing and no eviction (when all probe @@ -33,9 +31,9 @@ const CAPACITY: usize = 16_384; /// Minimum string length eligible for caching. /// -/// Empty strings and single-ASCII-character strings are already interned by -/// `allocate_string`, so caching them would be redundant. -const MIN_LEN: usize = 2; +/// Strings up to 15 UTF-8 bytes are interned or stored inline, so caching them +/// would be redundant. +const MIN_LEN: usize = 16; /// Maximum string length eligible for caching. /// @@ -54,7 +52,7 @@ type CacheEntry = Option<(u64, Box, Value)>; /// /// - Created as empty (`None`) when the VM starts. /// - Backing storage allocated on the first `get_or_allocate` call with an -/// eligible string (2–64 bytes). +/// eligible string (16–64 bytes). /// - Persists across multiple `json.loads()` calls within the same run. /// - Cleaned up when the VM is dropped via [`drop_all`](Self::drop_all). /// - Cached values keep themselves alive via the refcount on each cached @@ -161,3 +159,40 @@ impl CacheInner { value } } + +#[cfg(test)] +mod tests { + use monty_types::ResourceTracker; + + use super::*; + use crate::{heap::Heap, value::Value}; + + #[test] + fn inline_strings_bypass_the_cache() { + let mut cache = JsonStringCache::default(); + let mut heap = Heap::new(16, ResourceTracker::default()); + + HeapReader::with(&mut heap, &mut (), |reader, ()| { + let value = cache.get_or_allocate("123456789012345".to_owned(), reader); + assert!(matches!(value, Value::InlineString(_))); + }); + + assert!(cache.inner.is_none()); + } + + #[test] + fn sixteen_byte_strings_use_the_cache() { + let mut cache = JsonStringCache::default(); + let mut heap = Heap::new(16, ResourceTracker::default()); + + HeapReader::with(&mut heap, &mut (), |reader, ()| { + let first = cache.get_or_allocate("1234567890123456".to_owned(), reader); + let second = cache.get_or_allocate("1234567890123456".to_owned(), reader); + assert!(matches!((&first, &second), (Value::Ref(a), Value::Ref(b)) if a == b)); + first.drop_with(reader); + second.drop_with(reader); + }); + assert!(cache.inner.is_some()); + cache.drop_all(&mut heap); + } +} diff --git a/crates/bashkit-monty/src/modules/mod.rs b/crates/bashkit-monty/src/modules/mod.rs index ac570f66d..c973ec9c9 100644 --- a/crates/bashkit-monty/src/modules/mod.rs +++ b/crates/bashkit-monty/src/modules/mod.rs @@ -14,6 +14,7 @@ use crate::{ intern::StaticStrings, }; +pub(crate) mod annotationlib; pub(crate) mod asyncio; pub(crate) mod base64; pub(crate) mod binascii; @@ -24,6 +25,7 @@ pub(crate) mod csv; pub(crate) mod dataclasses; pub(crate) mod datetime; pub(crate) mod decimal; +pub(crate) mod fnmatch; pub(crate) mod functools; #[cfg(feature = "test-hooks")] pub(crate) mod gc; @@ -101,6 +103,10 @@ pub(crate) enum StandardLib { Tomllib, /// The `decimal` module: `Decimal`, `Context` and the signals. Decimal, + /// The `fnmatch` module: shell-style pattern matching. + Fnmatch, + /// The `annotationlib` module: `Format`, `ForwardRef` and `get_annotations()`. + Annotationlib, /// The `gc` module exposing a single `collect()` for tests. Only present /// under the `test-hooks` feature so production sandboxes never see it. /// @@ -137,6 +143,8 @@ impl StandardLib { StaticStrings::Csv => Some(Self::Csv), StaticStrings::Tomllib => Some(Self::Tomllib), StaticStrings::DecimalMod => Some(Self::Decimal), + StaticStrings::Fnmatch => Some(Self::Fnmatch), + StaticStrings::Annotationlib => Some(Self::Annotationlib), #[cfg(feature = "test-hooks")] StaticStrings::Gc => Some(Self::Gc), _ => None, @@ -179,6 +187,8 @@ impl StandardLib { Self::Csv => csv::create_module(vm), Self::Tomllib => tomllib::create_module(vm), Self::Decimal => decimal::create_module(vm), + Self::Fnmatch => fnmatch::create_module(vm), + Self::Annotationlib => annotationlib::create_module(vm), #[cfg(feature = "test-hooks")] Self::Gc => gc::create_module(vm), } @@ -214,6 +224,9 @@ pub(crate) enum ModuleFunctions { Csv(csv::CsvFunctions), Tomllib(tomllib::TomllibFunctions), Decimal(decimal::DecimalFunctions), + Fnmatch(fnmatch::FnmatchFunctions), + Typing(typing::TypingFunctions), + Annotationlib(annotationlib::AnnotationlibFunctions), /// `gc` module functions — only present under the `test-hooks` feature. /// See [`gc`] for why it is gated; as in [`StandardLib`], the gated block /// goes last and new variants are appended ahead of it. @@ -252,6 +265,9 @@ impl fmt::Display for ModuleFunctions { Self::Csv(func) => write!(f, "{func}"), Self::Tomllib(func) => write!(f, "{func}"), Self::Decimal(func) => write!(f, "{func}"), + Self::Fnmatch(func) => write!(f, "{func}"), + Self::Typing(func) => write!(f, "{func}"), + Self::Annotationlib(func) => write!(f, "{func}"), #[cfg(feature = "test-hooks")] Self::Gc(func) => write!(f, "{func}"), #[cfg(feature = "test-hooks")] @@ -289,6 +305,9 @@ impl ModuleFunctions { Self::Csv(functions) => csv::call(vm, functions, args), Self::Tomllib(functions) => tomllib::call(vm, functions, args), Self::Decimal(functions) => decimal::call(vm, functions, args).map(CallResult::Value), + Self::Fnmatch(functions) => fnmatch::call(vm, functions, args).map(CallResult::Value), + Self::Typing(functions) => typing::call(vm, functions, args), + Self::Annotationlib(functions) => annotationlib::call(vm, functions, args), #[cfg(feature = "test-hooks")] Self::Gc(functions) => gc::call(vm, functions, args).map(CallResult::Value), #[cfg(feature = "test-hooks")] diff --git a/crates/bashkit-monty/src/modules/os.rs b/crates/bashkit-monty/src/modules/os.rs index d559d0031..430b01397 100644 --- a/crates/bashkit-monty/src/modules/os.rs +++ b/crates/bashkit-monty/src/modules/os.rs @@ -178,12 +178,8 @@ fn scandir(vm: &mut VM<'_>, args: ArgValues) -> RunResult { } else { extract_os_path(path, "scandir", "path", PathAccepts::FdOrNone, vm)? }; - if path.is_empty() { - // The host would scan the working directory; CPython fails with ENOENT. - Err(ExcType::file_not_found_error("")) - } else { - Ok(scandir_call(path)) - } + // An empty path fails with ENOENT at the VM's OS-call exit, as in CPython. + Ok(scandir_call(path)) } /// `os.walk(top, topdown=True, onerror=None, followlinks=False)` argument @@ -330,7 +326,7 @@ fn getenv(vm: &mut VM<'_>, args: ArgValues) -> RunResult { key_value.drop_with(vm.heap); Ok(CallResult::OsCall(OsFunctionCall::Getenv(GetenvArgs { key: key.into_string(vm.interns), - default: MontyObject::export(default_value.unwrap_or(Value::None), vm), + default: MontyObject::export(default_value.unwrap_or(Value::None), vm)?, }))) } else { let type_name = key_value.py_type_name_heap(vm.heap, vm.interns); diff --git a/crates/bashkit-monty/src/modules/os_path/mod.rs b/crates/bashkit-monty/src/modules/os_path/mod.rs index 765535285..adaabc75b 100644 --- a/crates/bashkit-monty/src/modules/os_path/mod.rs +++ b/crates/bashkit-monty/src/modules/os_path/mod.rs @@ -719,6 +719,7 @@ fn lexists(vm: &mut VM<'_>, args: ArgValues) -> RunResult { let LexistsArgs { path } = LexistsArgs::from_args(args, vm)?; defer_drop!(path, vm); let path = extract_os_path(path, "lstat", "path", PathAccepts::NoFd, vm)?; + // answered locally: a call made from a builtin such as `map()` cannot suspend if path.is_empty() { Ok(CallResult::Value(Value::Bool(false))) } else { @@ -763,6 +764,8 @@ fn samefile(vm: &mut VM<'_>, args: ArgValues) -> RunResult { defer_drop!(f1, vm); defer_drop!(f2, vm); let first = extract_os_path(f1, "stat", "path", PathAccepts::Fd, vm)?; + // raised locally, as a call from a builtin such as `map()` cannot suspend; + // `prepare_os_call` rejects an empty second path if first.is_empty() { return Err(ExcType::file_not_found_error("")); } @@ -779,8 +782,7 @@ fn samefile(vm: &mut VM<'_>, args: ArgValues) -> RunResult { /// Moves `os.path.samefile` from its first `Path.stat` to its second — the /// resume half of [`PreConversionEffect::SamefileFirst`]. The second path's -/// deferred converter error and `FileNotFoundError` for the empty path raise -/// here, where CPython's `os.stat(f2)` raises them. +/// deferred converter error raises here, where CPython's `os.stat(f2)` raises it. pub(crate) fn samefile_first_reply( value: &MontyObject, first: String, @@ -788,11 +790,7 @@ pub(crate) fn samefile_first_reply( ) -> Result { let first_identity = stat_identity(value).ok_or_else(|| invalid_reply("os.path.samefile", "a stat result", value))?; - let second = match second { - Ok(second) if second.is_empty() => return Err(ExcType::file_not_found_error("")), - Ok(second) => second, - Err(err) => return Err(err.into_error("stat", "path")), - }; + let second = second.map_err(|err| err.into_error("stat", "path"))?; Ok(Reshaped::Call { call: OsFunctionCall::Stat(MontyPath::new(second.clone())), effect: Some( @@ -917,7 +915,8 @@ fn getctime(vm: &mut VM<'_>, args: ArgValues) -> RunResult { /// Shared body of the stat getters: the `Path.stat` host call with a /// [`PreConversionEffect::StatField`] that keeps one field of the reply. The -/// empty path fails as CPython's `stat('')` does, without consulting the host. +/// empty path fails as CPython's `stat('')` does, without suspending, so a call +/// from a builtin such as `map()` still raises `FileNotFoundError`. fn stat_field(path: &Value, field: StatField, vm: &VM<'_>) -> RunResult { let path = extract_os_path(path, "stat", "path", PathAccepts::Fd, vm)?; if path.is_empty() { diff --git a/crates/bashkit-monty/src/modules/pathlib.rs b/crates/bashkit-monty/src/modules/pathlib.rs index 79187ff95..83082cfa9 100644 --- a/crates/bashkit-monty/src/modules/pathlib.rs +++ b/crates/bashkit-monty/src/modules/pathlib.rs @@ -11,7 +11,7 @@ use crate::{ bytecode::VM, heap::{HeapData, HeapId}, intern::StaticStrings, - types::{Module, Type}, + types::{BuiltinType, Module}, value::Value, }; @@ -21,7 +21,11 @@ pub fn create_module(vm: &mut VM<'_>) -> HeapId { let mut module = Module::new(StaticStrings::Pathlib, vm.interns); // pathlib.Path - the Path class (callable to create Path instances) - module.set_attr(StaticStrings::PathClass, Value::Builtin(Builtins::Type(Type::Path)), vm); + module.set_attr( + StaticStrings::PathClass, + Value::Builtin(Builtins::Type(BuiltinType::Path)), + vm, + ); vm.heap.allocate(HeapData::Module(Box::new(module))) } diff --git a/crates/bashkit-monty/src/modules/random.rs b/crates/bashkit-monty/src/modules/random.rs index 0fbcb618f..5ecbbe03f 100644 --- a/crates/bashkit-monty/src/modules/random.rs +++ b/crates/bashkit-monty/src/modules/random.rs @@ -36,7 +36,7 @@ use crate::{ modules::ModuleFunctions, os_dispatch::{PostConversionEffect, urandom_reply_error}, types::{ - List, LongInt, Module, PyTrait, Type, + BuiltinType, List, LongInt, Module, PyTrait, Type, bytes::allocate_bytes, iter::collect_owned_iterable, long_int::bigint_to_f64_checked, @@ -122,7 +122,7 @@ pub fn create_module(vm: &mut VM<'_>) -> HeapId { } module.set_attr( StaticStrings::RandomClass, - Value::Builtin(Builtins::Type(Type::Random)), + Value::Builtin(Builtins::Type(BuiltinType::Random)), vm, ); vm.heap.allocate(HeapData::Module(Box::new(module))) @@ -376,7 +376,7 @@ fn setstate(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult other => { let text = other.py_str(vm)?; defer_drop!(text, vm); - let text = text.to_str_heap(vm.heap, vm.interns)?; + let text = text.as_str_heap(vm.heap, vm.interns).expect("py_str returns str"); return Err(ExcType::value_error(format!( "state with version {text} passed to Random.setstate() of version 3" ))); @@ -971,7 +971,7 @@ fn choices(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult< defer_drop!(k, vm); return Err(ExcType::type_error(format!( "The number of choices must be a keyword argument: k={}", - k.to_str_heap(vm.heap, vm.interns)? + k.as_str_heap(vm.heap, vm.interns).expect("py_str returns str") ))); } else { Some(cumulative_weights(weights, vm)?) diff --git a/crates/bashkit-monty/src/modules/re.rs b/crates/bashkit-monty/src/modules/re.rs index 588f11f64..0ed0bf584 100644 --- a/crates/bashkit-monty/src/modules/re.rs +++ b/crates/bashkit-monty/src/modules/re.rs @@ -12,7 +12,7 @@ //! - `re.findall(pattern, string, flags=0)` → `list` //! - `re.sub(pattern, repl, string, count=0, flags=0)` → `str` //! - `re.split(pattern, string, maxsplit=0, flags=0)` → `list` -//! - `re.finditer(pattern, string, flags=0)` → iterator of `re.Match` +//! - `re.finditer(pattern, string, flags=0)` → `list` of `re.Match` (CPython: an iterator) //! - `re.escape(pattern)` → `str` //! //! Like CPython's pure-Python `re` functions, all arguments are accepted @@ -44,7 +44,7 @@ use crate::{ intern::StaticStrings, modules::ModuleFunctions, types::{ - BoundedCompileError, Module, RePattern, Type, + BoundedCompileError, BuiltinType, Module, RePattern, Type, re_pattern::{extract_count, extract_maxsplit, translate_replacement}, str::allocate_string, }, @@ -82,7 +82,7 @@ pub(crate) enum ReFunctions { Sub, /// `re.split(pattern, string, maxsplit=0, flags=0)` — split string by pattern. Split, - /// `re.finditer(pattern, string, flags=0)` — return iterator over all matches. + /// `re.finditer(pattern, string, flags=0)` — return a list of all matches. Finditer, /// `re.escape(pattern)` — escape all non-alphanumeric characters in pattern. Escape, @@ -167,12 +167,12 @@ pub fn create_module(vm: &mut VM<'_>) -> HeapId { // Constructed types module.set_attr( StaticStrings::PatternClass, - Value::Builtin(Builtins::Type(Type::RePattern)), + Value::Builtin(Builtins::Type(BuiltinType::RePattern)), vm, ); module.set_attr( StaticStrings::MatchClass, - Value::Builtin(Builtins::Type(Type::ReMatch)), + Value::Builtin(Builtins::Type(BuiltinType::ReMatch)), vm, ); @@ -282,7 +282,7 @@ fn call_sub(vm: &mut VM<'_>, args: ArgValues) -> RunResult { // CPython parses the replacement template before its match loop, so a bad // replacement raises even when a negative count skips matching. - let Ok(repl) = repl.to_str(vm) else { + let Some(repl) = repl.as_str(vm) else { return Err(ExcType::type_error( "callable replacement is not yet supported in re.sub()", )); @@ -456,8 +456,8 @@ struct ReFinditerArgs { /// pattern, and flags errors always win. Monty has no bytes matching: a bytes subject /// gets CPython's mixed-types message, anything else the `sre` wording. fn subject_str<'a>(value: &'a Value, vm: &'a VM<'_>) -> RunResult<&'a str> { - if value.is_str(vm.heap) { - value.to_str(vm) + if let Some(text) = value.as_str(vm) { + Ok(text) } else if value.py_type_heap(vm.heap) == Type::Bytes { // Monty patterns are always str, so a bytes subject is always // CPython's string-pattern/bytes-subject mismatch. @@ -727,8 +727,9 @@ fn resolve_pattern(pattern: Value, flags: Value, vm: &mut VM<'_>) -> RunResult, args: ArgValues) -> RunResult { let ReFinditerArgs { pattern, string, flags } = ReFinditerArgs::from_args(args, vm)?; defer_drop!(string, vm); @@ -744,7 +745,7 @@ fn call_finditer(vm: &mut VM<'_>, args: ArgValues) -> RunResult { fn call_escape(vm: &mut VM<'_>, args: ArgValues) -> RunResult { let ReEscapeArgs { pattern } = ReEscapeArgs::from_args(args, vm)?; defer_drop!(pattern, vm); - let Ok(text) = pattern.to_str(vm) else { + let Some(text) = pattern.as_str(vm) else { // CPython's escape() falls back to `str(pattern, 'latin1')` for // non-str input, so this is the (incidental) message it raises. let t = pattern.py_type_name(vm); diff --git a/crates/bashkit-monty/src/modules/time.rs b/crates/bashkit-monty/src/modules/time.rs index 89e79d737..0fae6dd6e 100644 --- a/crates/bashkit-monty/src/modules/time.rs +++ b/crates/bashkit-monty/src/modules/time.rs @@ -28,7 +28,7 @@ use crate::{ string_builder::StringBuilder, types::{ Module, NamedTuple, PyTrait, date, datetime as datetime_type, - datetime::{sandbox_instant, sandbox_local_wall_clock}, + datetime::{TimestampRounding, sandbox_instant, sandbox_local_wall_clock}, str::allocate_string, timezone::tzname_string, tuple::allocate_tuple, @@ -298,7 +298,7 @@ fn sleep(vm: &mut VM<'_>, args: ArgValues) -> RunResult { .get_one_arg("time.sleep", vm.heap)?; let result = sleep_seconds(&seconds, vm).and_then(|secs| { sleep_duration(secs).map_err(|err| match err { - SleepError::NotANumber => ExcType::value_error("Invalid value NaN (not a number)"), + SleepError::NotANumber => ExcType::invalid_nan(), SleepError::Negative => ExcType::value_error("sleep length must be non-negative"), SleepError::TooLarge => ExcType::sleep_too_long(), }) @@ -477,7 +477,7 @@ fn suspend_or_apply(vm: &mut VM<'_>, caller: TimeCaller, reading: ClockReading) /// The `str` at position `position` of a `time` function's arguments, /// with `_PyArg_BadArgument`'s positional wording. fn string_arg(value: &Value, name: &str, position: usize, vm: &VM<'_>) -> RunResult { - match value.to_str(vm) { + match value.try_to_str(vm) { Ok(text) => Ok(text.to_owned()), Err(_) => Err(ExcType::type_error(format!( "{name}() argument {position} must be str, not {}", @@ -776,7 +776,7 @@ fn time_tuple_parts(value: &Value, name: &str, vm: &VM<'_>) -> RunResult<([i64; Some([Value::Int(offset_seconds), name]) => { i32::try_from(*offset_seconds).ok().map(|offset_seconds| MontyTimeZone { offset_seconds, - name: name.to_str(vm).ok().map(str::to_owned), + name: name.as_str(vm).map(str::to_owned), }) } _ => None, @@ -831,42 +831,21 @@ fn tuple_zone(year: i32, isdst: i64, vm: &VM<'_>) -> Option { fn optional_instant(seconds: &Value, vm: &mut VM<'_>) -> RunResult> { match seconds { Value::None => sandbox_instant(vm), - value => { - let seconds = clock_seconds(value, vm)?; - instant_from_seconds(seconds).map(Some) - } - } -} - -/// The `secs` argument of `gmtime`/`localtime`/`ctime` as float seconds. -/// -/// Like [`sleep_seconds`] a float passes through and anything else goes through -/// `__index__`, but CPython's `_PyTime_ObjectToTime_t` reports a rejection as a -/// plain non-integer rather than naming floats as acceptable. -fn clock_seconds(value: &Value, vm: &mut VM<'_>) -> RunResult { - match value { - Value::Float(f) => Ok(*f), - _ => match value.py_index_impl(vm)? { - Some(index) => { - let seconds = index_seconds(&index, vm); - index.drop_with(vm); - Ok(seconds) - } - None => Err(ExcType::type_error(format!( - "'{}' object cannot be interpreted as an integer", - value.py_type_name(vm) - ))), + // CPython's `_PyTime_ObjectToTime_t` floors to whole seconds, as for + // `date.fromtimestamp()`, but words a rejection as a plain non-integer. + value => match datetime_type::timestamp_parts(value, TimestampRounding::Floor, vm)? { + Some((whole, _)) => instant_in_range(whole, 0).map(Some), + None => Err(ExcType::type_error_not_integer(&value.py_type_name(vm))), }, } } -/// Epoch seconds as an instant. The whole seconds floor, as CPython's -/// `_PyTime_ObjectToTime_t` does for `gmtime(-1.9)`, and the fraction is kept -/// so the `_ns` clocks see it; the broken-down fields never read it. +/// The host's `time.time` answer as an instant. The whole seconds floor and the +/// fraction is kept to the nanosecond so the `_ns` clocks see it. fn instant_from_seconds(seconds: f64) -> RunResult { let floored = seconds.floor(); if floored.is_nan() { - return Err(ExcType::value_error("Invalid value NaN (not a number)")); + return Err(ExcType::invalid_nan()); } // `as` saturates, which would silently clamp rather than raise. if !(-9.3e18..=9.3e18).contains(&floored) { @@ -883,6 +862,12 @@ fn instant_from_seconds(seconds: f64) -> RunResult { reason = "a fraction in 0..1, scaled" )] let nanos = (((seconds - floored) * 1e9).round() as u32).min(999_999_999); + instant_in_range(whole, nanos) +} + +/// Epoch seconds as an instant, raising the `time_t` overflow outside years +/// 1..=9999, which a `struct_time` here cannot leave. +fn instant_in_range(whole: i64, nanos: u32) -> RunResult { DateTime::from_timestamp(whole, nanos) .map(|utc| utc.naive_utc()) .filter(|utc| local_wall_clock(*utc, 0).is_some()) diff --git a/crates/bashkit-monty/src/modules/tomllib/mod.rs b/crates/bashkit-monty/src/modules/tomllib/mod.rs index ba495c1be..adbfbfafe 100644 --- a/crates/bashkit-monty/src/modules/tomllib/mod.rs +++ b/crates/bashkit-monty/src/modules/tomllib/mod.rs @@ -101,10 +101,10 @@ struct TomlLoadsArgs { fn call_loads(vm: &mut VM<'_>, args: ArgValues) -> RunResult { let TomlLoadsArgs { s } = TomlLoadsArgs::from_args(args, vm)?; defer_drop!(s, vm); - let table = match s.to_str(vm) { - Ok(source) => parse_document(source, &vm.heap.tracker)?, - Err(_) => return Err(ExcType::toml_loads_type_error(&s.py_type_name(vm))), - }; + let source = s + .as_str(vm) + .ok_or_else(|| ExcType::toml_loads_type_error(&s.py_type_name(vm)))?; + let table = parse_document(source, &vm.heap.tracker)?; value::table_into_value(table, vm) } diff --git a/crates/bashkit-monty/src/modules/typing.rs b/crates/bashkit-monty/src/modules/typing.rs index 6b46709b0..1b294694e 100644 --- a/crates/bashkit-monty/src/modules/typing.rs +++ b/crates/bashkit-monty/src/modules/typing.rs @@ -4,17 +4,33 @@ //! - `TYPE_CHECKING`: Always False (used for conditional imports) //! - Common type hints as `Marker` values (Any, Optional, List, Dict, etc.) //! - `Union`, the type behind `int | None` (see `types/union.rs`) +//! - `ForwardRef`, shared with `annotationlib` (see `types/forward_ref.rs`) +//! - `get_type_hints()`, evaluating annotations from their `__annotate__` +//! function (PEP 649) in any `annotationlib.Format`; +//! `annotationlib.get_annotations()` shares its machinery through [`collect_hints`] //! //! These markers exist so code that imports typing constructs works correctly, //! though Monty doesn't perform static type checking. `Optional[X]` is the one //! marker that can be subscripted, producing `X | None`. +use monty_types::{OsFunctionCall, TypeHintsTarget}; +use smallvec::SmallVec; + use crate::{ - builtins::Builtins, - bytecode::VM, + annotations::{self, empty_dict}, + args::{ArgValues, FromArgs}, + builtins::{Builtins, BuiltinsFunctions, eval_exec}, + bytecode::{CallResult, MissingNames, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + frozen::{FrozenFunction, FrozenFunctions}, heap::{HeapData, HeapId}, - intern::StaticStrings, - types::{Module, Type}, + intern::{FunctionId, StaticStrings}, + modules::ModuleFunctions, + types::{ + BuiltinType, LazyHeapSet, Module, PyTrait, allocate_string, allocate_tuple, forward_ref::format_code, + generic_alias::repr_type_arg, + }, value::{Marker, Value}, }; @@ -30,7 +46,13 @@ pub fn create_module(vm: &mut VM<'_>) -> HeapId { // `types.UnionType` since 3.14), so it is a real type rather than a marker. module.set_attr( StaticStrings::UnionType, - Value::Builtin(Builtins::Type(Type::Union)), + Value::Builtin(Builtins::Type(BuiltinType::Union)), + vm, + ); + // `typing.ForwardRef is annotationlib.ForwardRef` in CPython. + module.set_attr( + StaticStrings::ForwardRef, + Value::Builtin(Builtins::Type(BuiltinType::ForwardRef)), vm, ); @@ -39,6 +61,12 @@ pub fn create_module(vm: &mut VM<'_>) -> HeapId { module.set_attr(*ss, Value::Marker(Marker(*ss)), vm); } + module.set_attr( + StaticStrings::GetTypeHints, + Value::ModuleFunction(ModuleFunctions::Typing(TypingFunctions::GetTypeHints)), + vm, + ); + vm.heap.allocate(HeapData::Module(Box::new(module))) } @@ -72,3 +100,694 @@ const MARKER_ATTRS: &[StaticStrings] = &[ StaticStrings::Never, StaticStrings::NoReturn, ]; + +/// `typing` module functions, each a Python-visible callable. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "snake_case")] +pub(crate) enum TypingFunctions { + GetTypeHints, +} + +/// Dispatches a `typing` module function call. +pub(super) fn call(vm: &mut VM<'_>, function: TypingFunctions, args: ArgValues) -> RunResult { + match function { + TypingFunctions::GetTypeHints => get_type_hints(vm, args), + } +} + +/// Evaluates annotations as CPython 3.14's `annotationlib.get_annotations` and +/// `typing.get_type_hints` do, from an `__annotate__` function or a stored dict. +/// +/// `annotate` and `stored` are the object's `__annotate__` function and bound +/// `__annotations__` dict (`None` when absent), `classdict` a copy of a class's +/// namespace, and `scopes` `(globals, locals, globals_first)`: where a forward +/// reference evaluates. `format_` is the `annotationlib.Format` code, `task` 0 +/// for `get_annotations`, 1 for it with `eval_str=True` and 2 for +/// `get_type_hints`. `call_annotate` runs the function with a format and a +/// fake-globals mode (0 none, 1 stringify unresolved names, 2 every name, 3 +/// raise `NameError` without asking the host); +/// `cache`, for a class, stores a plain evaluation as CPython's +/// `type.__annotations__` would. `eval_hint`'s last three arguments are the +/// name mode, the owner and the class flag. +pub(crate) const GET_ANNOTATIONS_SOURCE: &str = r" +def __monty_get_annotations(owner, annotate, stored, classdict, scopes, format_, task, include_extras, is_class, call_annotate, cache, eval_hint, alias_with, forward_ref, type_repr_, isinstance_, len_, str_, tuple_, dict_, repr_, generic_alias, literal_, union, none_type, exception, not_implemented_error, syntax_error, value_error): + VALUE = 1 + FAKE_GLOBALS = 2 + FORWARDREF = 3 + STRING = 4 + fwd_globalns, fwd_localns, fwd_globals_first = scopes + # `annotationlib.get_annotations`: a stored dict is reported as is (STRING + # prefers the function, so a cached evaluation never hides the source); + # otherwise `__annotate__` runs, first asked for the format itself (a + # hand-written one may support it), then under fake globals + # (`call_annotate_function`). + if format_ == STRING: + if annotate is None: + annotations = stored + else: + try: + annotations = call_annotate(annotate, classdict, STRING, 0, owner, is_class) + except not_implemented_error: + try: + annotations = call_annotate(annotate, classdict, FAKE_GLOBALS, 2, owner, is_class) + except not_implemented_error: + annotations = call_annotate(annotate, classdict, VALUE, 0, owner, is_class) + if not isinstance_(annotations, dict_): + raise value_error(repr_(owner) + '.__annotate__ returned a non-dict') + result = {} + for name, value in annotations.items(): + if isinstance_(value, forward_ref): + value = value.__forward_arg__ + elif value is ...: + value = '...' + elif not isinstance_(value, str_): + value = type_repr_(value) + result[name] = value + return result + if stored is not None: + annotations = stored + elif format_ == VALUE: + annotations = call_annotate(annotate, classdict, VALUE, 0, owner, is_class) + if cache is not None: + cache(owner, annotations) + else: + # FORWARDREF: the plain evaluation `__annotations__` makes first, which a + # class caches; it raises `NameError` where it would ask the host for a + # name, so this format never does. Then `call_annotate_function`: the + # function's own support, else fake globals stringifying unresolved + # names, and if that run raises, every name is stringified and each + # reference then evaluated on its own. + # A non-dict from the plain evaluation is the `TypeError` `__annotations__` + # raises, which `get_annotations` swallows like any other failure. + plain = True + try: + annotations = call_annotate(annotate, classdict, VALUE, 3, owner, is_class) + except exception: + plain = False + if plain and not isinstance_(annotations, dict_): + plain = False + if plain: + if cache is not None: + cache(owner, annotations) + else: + try: + annotations = call_annotate(annotate, classdict, FORWARDREF, 0, owner, is_class) + except not_implemented_error: + try: + annotations = call_annotate(annotate, classdict, FAKE_GLOBALS, 1, owner, is_class) + except exception: + annotations = call_annotate(annotate, classdict, FAKE_GLOBALS, 2, owner, is_class) + if not isinstance_(annotations, dict_): + raise value_error(repr_(owner) + '.__annotate__ returned a non-dict') + evaluated = {} + for name, value in annotations.items(): + if isinstance_(value, forward_ref): + value = value.evaluate(format=FORWARDREF) + evaluated[name] = value + annotations = evaluated + if not isinstance_(annotations, dict_): + raise value_error(repr_(owner) + '.__annotate__ returned a non-dict') + # `get_annotations(eval_str=True)` evaluates string values with plain `eval()`. + if task == 1: + result = {} + for name, value in annotations.items(): + if isinstance_(value, str_): + value = eval_hint(value, fwd_globalns, fwd_localns, False, False, 0, None, False) + result[name] = value + return result + if task != 2: + result = {} + for name, value in annotations.items(): + result[name] = value + return result + # Pass 2, `typing._eval_type`: resolve forward references at any depth of a + # generic alias or union (`alias_with` also strips `Annotated` unless + # `include_extras`). An explicit stack, since frozen code cannot recurse; each frame is + # [value, resolved args or None, texts seen, next index, parent reference]. + result = {} + for name, value in annotations.items(): + if isinstance_(value, str_): + value = forward_ref(value, is_argument=not is_class, is_class=is_class) + stack = [[value, None, (), 0, None]] + while stack: + frame = stack[-1] + value = frame[0] + if frame[1] is None: + seen = frame[2] + parent = frame[4] + # `evaluate_forward_ref`: follow the chain of references, stopping + # at one seen before (`a = 'a'`) or, in FORWARDREF, one that stays unresolved. + while isinstance_(value, forward_ref): + text = value.__forward_arg__ + if text in seen: + break + if format_ == FORWARDREF: + try: + evaluated = eval_hint(text, fwd_globalns, fwd_localns, fwd_globals_first, True, 1, owner, value.__forward_is_class__) + except syntax_error: + raise + except exception: + break + if isinstance_(evaluated, forward_ref): + if not text.isidentifier(): + value = evaluated + break + else: + evaluated = eval_hint(text, fwd_globalns, fwd_localns, fwd_globals_first, True, 0, None, False) + seen = seen + (text,) + parent = value + if isinstance_(evaluated, str_): + evaluated = forward_ref(evaluated, module=value.__forward_module__, owner=owner, is_argument=value.__forward_is_argument__, is_class=value.__forward_is_class__) + value = evaluated + # A `Literal` holds values, not types: its strings stay strings. + if (isinstance_(value, generic_alias) and value.__origin__ is not literal_) or isinstance_(value, union): + frame[0] = value + frame[1] = [] + frame[2] = seen + frame[4] = parent + else: + stack.pop() + if stack: + stack[-1][1].append(value) + continue + args = value.__args__ + index = frame[3] + if index < len_(args): + frame[3] = index + 1 + arg = args[index] + if isinstance_(arg, str_): + parent = frame[4] + if parent is None or isinstance_(value, union): + arg = forward_ref(arg) + else: + arg = forward_ref(arg, module=parent.__forward_module__, owner=parent.__owner__) + stack.append([arg, None, frame[2], 0, None]) + continue + resolved = tuple_(frame[1]) + if isinstance_(value, generic_alias): + value = alias_with(value, resolved, include_extras) + elif resolved != args: + value = resolved[0] + for member in resolved[1:]: + value = value | member + stack.pop() + if stack: + stack[-1][1].append(value) + if value is None: + value = none_type + result[name] = value + return result +"; + +/// Arguments of `typing.get_type_hints(obj, globalns=None, localns=None, include_extras=False, *, format=None)`. +#[derive(FromArgs)] +#[from_args(name = "get_type_hints", style = def)] +struct GetTypeHintsArgs { + obj: Value, + #[from_args(default = Value::None)] + globalns: Value, + #[from_args(default = Value::None)] + localns: Value, + #[from_args(default = Value::Bool(false))] + include_extras: Value, + #[from_args(kw_only, default = Value::None)] + format: Value, +} + +/// `typing.get_type_hints()`: see [`collect_hints`]. +fn get_type_hints(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let GetTypeHintsArgs { + obj, + globalns, + localns, + include_extras, + format, + } = GetTypeHintsArgs::from_args(args, vm)?; + defer_drop!(obj, vm); + defer_drop!(globalns, vm); + defer_drop!(localns, vm); + defer_drop!(include_extras, vm); + defer_drop!(format, vm); + + // CPython reads `__no_type_check__` before it looks at anything else. + if let HintSource::Class(class_id) = hint_source(obj, vm) + && class_attr_is_true(class_id, "__no_type_check__", vm)? + { + return Ok(CallResult::Value(empty_dict(vm))); + } + let format = HintFormat::parse(format, true, vm)?; + let globalns = namespace_dict(globalns, "get_type_hints", "globalns", vm)?; + let localns = namespace_dict(localns, "get_type_hints", "localns", vm)?; + let include_extras = include_extras.py_bool(vm)?; + collect_hints( + obj, + &HintsRequest { + format, + globalns, + localns, + include_extras, + task: HintsTask::TypeHints, + }, + vm, + ) +} + +/// How an annotation is reported: the `annotationlib.Format` members Monty implements. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum HintFormat { + /// `VALUE`: the evaluated object. + Value, + /// `FORWARDREF`: the evaluated object, with each unresolved name a `ForwardRef`. + ForwardRef, + /// `STRING`: the source text. + String, +} + +impl HintFormat { + /// The member `value` names, or CPython's `ValueError`; `None` is `VALUE` only + /// where `none_is_value` (`get_type_hints`, not `get_annotations`). + pub(crate) fn parse(value: &Value, none_is_value: bool, vm: &mut VM<'_>) -> RunResult { + match format_code(value) { + _ if none_is_value && matches!(value, Value::None) => Ok(Self::Value), + Some(1) => Ok(Self::Value), + Some(2) => Err(ExcType::value_error( + "The VALUE_WITH_FAKE_GLOBALS format is for internal use only", + )), + Some(3) => Ok(Self::ForwardRef), + Some(4) => Ok(Self::String), + _ => { + let repr = value.py_repr(vm)?; + defer_drop!(repr, vm); + Err(ExcType::value_error(format!( + "Unsupported format {}", + repr.as_str(vm).unwrap_or_default() + ))) + } + } + } + + /// The member's integer value, as the frozen evaluator takes it. + fn code(self) -> i64 { + match self { + Self::Value => 1, + Self::ForwardRef => 3, + Self::String => 4, + } + } +} + +/// What the caller wants done with the annotations. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum HintsTask { + /// `annotationlib.get_annotations()`: each annotation evaluated where it was + /// written, forward references left as strings unless `eval_str`. + Annotations { + /// Evaluate string values with `eval()` in the given or default namespaces. + eval_str: bool, + }, + /// `typing.get_type_hints()`: forward references resolved at any depth and + /// `None` reported as `NoneType`. + TypeHints, +} + +impl HintsTask { + /// The task code the frozen evaluator takes. + fn code(self) -> i64 { + match self { + Self::Annotations { eval_str: false } => 0, + Self::Annotations { eval_str: true } => 1, + Self::TypeHints => 2, + } + } + + /// The Python function's name, for error messages. + fn name(self) -> &'static str { + match self { + Self::Annotations { .. } => "get_annotations", + Self::TypeHints => "get_type_hints", + } + } +} + +/// One `get_type_hints()` / `get_annotations()` call's options. The namespaces are +/// borrowed dict ids, validated by [`namespace_dict`]. +pub(crate) struct HintsRequest { + pub format: HintFormat, + pub globalns: Option, + pub localns: Option, + /// `get_type_hints(include_extras=True)`: keep `Annotated` metadata. + pub include_extras: bool, + pub task: HintsTask, +} + +/// Finds `obj`'s `__annotate__` function or stored `__annotations__` and the +/// namespaces its forward references evaluate in, then hands them to the frozen +/// evaluator, which can push frames and suspend for host name lookups. A host +/// function or class suspends with an OS call instead: only the host can +/// evaluate its hints, in `VALUE` form. +pub(crate) fn collect_hints(obj: &Value, request: &HintsRequest, vm: &mut VM<'_>) -> RunResult { + match hint_source(obj, vm) { + HintSource::Function(func_id, globals) => { + let annotate = annotations::function_annotate(func_id, globals, vm); + defer_drop!(annotate, vm); + if matches!(annotate, Value::None) { + return Ok(CallResult::Value(empty_dict(vm))); + } + // A forward reference evaluates in `globalns` (default: the function's + // globals), then `localns` (default: `globalns`). + let scopes = ForwardRefScopes { + globals: request.globalns.or(globals), + locals: request.localns, + globals_first: false, + }; + let source = AnnotationSource { + annotate: annotate.clone_with_heap(vm), + stored: Value::None, + classdict: Value::None, + cache: false, + }; + resolve_hints(obj, source, scopes, false, request, vm) + } + HintSource::Class(class_id) => { + let stored = annotations::stored_class_annotations(class_id, vm); + defer_drop!(stored, vm); + // CPython's `annotationlib` rejects a non-dict binding such as `None`. + if let Some(stored) = stored + && !matches!(stored, Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::Dict(_))) + { + return Err(not_a_dict_error(class_id, vm)); + } + let annotate = annotations::class_annotate(class_id, vm); + defer_drop!(annotate, vm); + if stored.is_none() && annotate.is_none() { + return Ok(CallResult::Value(empty_dict(vm))); + } + // The annotations evaluate with a copy of the class namespace (CPython's + // `dict(vars(cls))`) over the module globals. + let classdict = annotations::class_namespace_copy(class_id, vm)?; + defer_drop!(classdict, vm); + let classdict_id = classdict.ref_id(); + let (globals, locals, globals_first) = match request.task { + // Without explicit namespaces `get_type_hints` searches the module + // globals before the class namespace, as CPython swaps them. + HintsTask::TypeHints => match (request.globalns, request.localns) { + (None, None) => (None, classdict_id, true), + (Some(_), None) => (request.globalns, classdict_id, false), + (_, Some(_)) => (request.globalns, request.localns, false), + }, + HintsTask::Annotations { .. } => (request.globalns, request.localns.or(classdict_id), false), + }; + let scopes = ForwardRefScopes { + globals, + locals, + globals_first, + }; + let source = AnnotationSource { + annotate: annotate.as_ref().map_or(Value::None, |value| value.clone_with_heap(vm)), + stored: stored.as_ref().map_or(Value::None, |value| value.clone_with_heap(vm)), + classdict: classdict.clone_with_heap(vm), + cache: true, + }; + resolve_hints(obj, source, scopes, true, request, vm) + } + HintSource::Host(target) => match request.format { + HintFormat::String => Err(ExcType::not_implemented(format!( + "{}() format=Format.STRING is not supported for host functions and classes", + request.task.name() + )) + .into()), + // The host evaluates its own hints; `FORWARDREF` is `VALUE` there. + HintFormat::Value | HintFormat::ForwardRef => Ok(CallResult::OsCall(OsFunctionCall::GetTypeHints(target))), + }, + HintSource::Empty => Ok(CallResult::Value(empty_dict(vm))), + HintSource::NotAnnotatable => Err(ExcType::no_annotations(obj, vm)), + } +} + +/// The namespaces a forward reference evaluates in: each a borrowed dict id or +/// `None` for the module slots (globals) or no locals. +struct ForwardRefScopes { + globals: Option, + locals: Option, + /// Bound module globals shadow `locals`. + globals_first: bool, +} + +impl ForwardRefScopes { + /// The `scopes` tuple the frozen evaluator takes, each dict a new reference. + fn into_tuple(self, vm: &VM<'_>) -> Value { + let mut items = SmallVec::new(); + for scope in [self.globals, self.locals] { + items.push(scope.map_or(Value::None, |id| { + vm.heap.inc_ref(id); + Value::Ref(id) + })); + } + items.push(Value::Bool(self.globals_first)); + allocate_tuple(items, vm.heap) + } +} + +/// What the frozen evaluator reads an object's annotations from, each an OWNED +/// value or `None`: its `__annotate__` function, its stored `__annotations__` +/// dict, and for a class the namespace copy its annotations evaluate under. +struct AnnotationSource { + annotate: Value, + stored: Value, + classdict: Value, + /// Cache a plain evaluation on the owner, as `type.__annotations__` does. + cache: bool, +} + +/// Runs the frozen evaluator for `owner`, consuming `source`. +fn resolve_hints( + owner: &Value, + source: AnnotationSource, + scopes: ForwardRefScopes, + is_class: bool, + request: &HintsRequest, + vm: &mut VM<'_>, +) -> RunResult { + let cache = if source.cache { + Value::ModuleFunction(ModuleFunctions::Frozen(FrozenFunctions::CacheClassAnnotations)) + } else { + Value::None + }; + let scopes = scopes.into_tuple(vm); + vm.call_frozen_exact( + FrozenFunction::GetAnnotations, + [ + owner.clone_with_heap(vm), + source.annotate, + source.stored, + source.classdict, + scopes, + Value::Int(request.format.code()), + Value::Int(request.task.code()), + Value::Bool(request.include_extras), + Value::Bool(is_class), + Value::ModuleFunction(ModuleFunctions::Frozen(FrozenFunctions::CallAnnotate)), + cache, + Value::ModuleFunction(ModuleFunctions::Frozen(FrozenFunctions::EvalHint)), + Value::ModuleFunction(ModuleFunctions::Frozen(FrozenFunctions::AliasWith)), + Value::Builtin(Builtins::Type(BuiltinType::ForwardRef)), + Value::ModuleFunction(ModuleFunctions::Frozen(FrozenFunctions::TypeRepr)), + Value::Builtin(Builtins::Function(BuiltinsFunctions::Isinstance)), + Value::Builtin(Builtins::Function(BuiltinsFunctions::Len)), + Value::Builtin(Builtins::Type(BuiltinType::Str)), + Value::Builtin(Builtins::Type(BuiltinType::Tuple)), + Value::Builtin(Builtins::Type(BuiltinType::Dict)), + Value::Builtin(Builtins::Function(BuiltinsFunctions::Repr)), + Value::Builtin(Builtins::Type(BuiltinType::GenericAlias)), + Value::Marker(Marker(StaticStrings::Literal)), + Value::Builtin(Builtins::Type(BuiltinType::Union)), + Value::Builtin(Builtins::Type(BuiltinType::NoneType)), + Value::Builtin(Builtins::ExcType(ExcType::Exception)), + Value::Builtin(Builtins::ExcType(ExcType::NotImplementedError)), + Value::Builtin(Builtins::ExcType(ExcType::SyntaxError)), + Value::Builtin(Builtins::ExcType(ExcType::ValueError)), + ], + ) +} + +/// Frozen helper: CPython's `annotationlib.type_repr`, a type by its name and +/// anything else by its repr, for `STRING` format. +pub(crate) fn call_type_repr(args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let value = args.get_one_arg("type_repr", vm.heap)?; + defer_drop!(value, vm); + let mut text = String::new(); + repr_type_arg(value, &mut text, vm, &mut LazyHeapSet::default())?; + Ok(allocate_string(text, vm.heap)) +} + +/// Where an object's annotations come from. +enum HintSource { + /// A `def`'s compiled annotations, and the `exec()` globals dict it was defined under. + Function(FunctionId, Option), + /// A sandbox class's `__annotations__`. + Class(HeapId), + /// An `ExtFunction` or `HostClassType`, whose hints the host evaluates on request. + Host(TypeHintsTarget), + /// A module or callable with no annotations Monty records: `{}`. + Empty, + /// Neither annotated nor callable: `TypeError`, as in CPython. + NotAnnotatable, +} + +/// Classifies `obj`, unwrapping bound methods and `lru_cache` wrappers (`__wrapped__`). +/// +/// A loop rather than recursion, so a deep chain of wrappers cannot exhaust the Rust stack. +fn hint_source(obj: &Value, vm: &VM<'_>) -> HintSource { + let mut current = obj; + loop { + let id = match current { + Value::DefFunction(func_id) => return HintSource::Function(*func_id, None), + Value::Ref(id) => *id, + value if value.is_callable(vm) => return HintSource::Empty, + _ => return HintSource::NotAnnotatable, + }; + current = match vm.heap.get(id) { + HeapData::FunctionDefaults(function) => return HintSource::Function(function.func_id, function.globals), + HeapData::Closure(closure) => return HintSource::Function(closure.func_id, closure.globals), + HeapData::Class(_) => return HintSource::Class(id), + HeapData::ExtFunction(function) => { + return HintSource::Host(TypeHintsTarget::Function(function.as_str().to_owned())); + } + HeapData::HostClassType(class) => return HintSource::Host(TypeHintsTarget::Class(class.type_id())), + HeapData::BoundMethod(method) => &method.func, + HeapData::LruCache(cache) => match cache.wrapped() { + Some(func) => func, + None => return HintSource::Empty, + }, + HeapData::Module(_) => return HintSource::Empty, + _ if current.is_callable(vm) => return HintSource::Empty, + _ => return HintSource::NotAnnotatable, + }; + } +} + +/// The globals `ForwardRef.evaluate()` defaults to for `owner`: a function's own +/// globals (`None` for the module slots), the module slots for a class, and an +/// empty dict for anything else, as CPython evaluates against `{}`. +pub(crate) fn owner_globals(owner: &Value, vm: &VM<'_>) -> Value { + match hint_source(owner, vm) { + HintSource::Function(_, Some(dict)) => { + vm.heap.inc_ref(dict); + Value::Ref(dict) + } + HintSource::Function(_, None) | HintSource::Class(_) => Value::None, + _ => empty_dict(vm), + } +} + +/// The locals `ForwardRef.evaluate()` defaults to for `owner`: a copy of a class's +/// namespace, nothing otherwise. +pub(crate) fn owner_locals(owner: &Value, vm: &mut VM<'_>) -> RunResult { + match hint_source(owner, vm) { + HintSource::Class(class_id) => annotations::class_namespace_copy(class_id, vm), + _ => Ok(Value::None), + } +} + +/// Whether the class namespace binds `name` to a truthy value; `typing.no_type_check` +/// classes set `__no_type_check__`, which makes `get_type_hints` return `{}`. +fn class_attr_is_true(class_id: HeapId, name: &str, vm: &mut VM<'_>) -> RunResult { + let HeapData::Class(class) = vm.heap.get(class_id) else { + unreachable!("hint_source classified a class"); + }; + let Some(value) = class.namespace().get_by_str(name, vm.heap, vm.interns) else { + return Ok(false); + }; + let value = value.clone_with_heap(vm.heap); + defer_drop!(value, vm); + value.py_bool(vm) +} + +/// The `ValueError` for a class whose `__annotations__` is bound to a non-dict. +fn not_a_dict_error(class_id: HeapId, vm: &mut VM<'_>) -> RunError { + vm.heap.inc_ref(class_id); + let class = Value::Ref(class_id); + defer_drop!(class, vm); + match class.py_repr(vm) { + Ok(repr) => { + defer_drop!(repr, vm); + let repr = repr.as_str(vm).map(str::to_owned).unwrap_or_default(); + ExcType::value_error(format!("{repr}.__annotations__ is neither a dict nor None")) + } + Err(err) => err, + } +} + +/// Validates a namespace argument of `function`: `None`, or a dict whose id is returned (borrowed). +pub(crate) fn namespace_dict(value: &Value, function: &str, param: &str, vm: &VM<'_>) -> RunResult> { + match value { + Value::None => Ok(None), + Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::Dict(_)) => Ok(Some(*id)), + _ => Err(ExcType::type_error(format!( + "{function}() {param} must be a dict, not {}", + value.py_type_name(vm) + ))), + } +} + +/// Arguments of the private annotation-evaluation primitive. +#[derive(FromArgs)] +#[from_args(name = "eval_hint")] +struct EvalHintArgs { + #[from_args(pos_only)] + source: Value, + #[from_args(pos_only)] + globals: Value, + #[from_args(pos_only)] + locals: Value, + #[from_args(pos_only)] + globals_first: Value, + #[from_args(pos_only)] + forward_ref: Value, + /// 0 raises `NameError`, 1 stringifies unresolved names, 2 stringifies every name. + #[from_args(pos_only)] + missing: Value, + #[from_args(pos_only)] + owner: Value, + #[from_args(pos_only)] + is_class: Value, +} + +/// Frozen helper: evaluates one annotation string; the namespaces are dicts or +/// `None`, built by [`collect_hints`] and never seen by user code. +pub(crate) fn call_eval_hint(args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let EvalHintArgs { + source, + globals, + locals, + globals_first, + forward_ref, + missing, + owner, + is_class, + } = EvalHintArgs::from_args(args, vm)?; + defer_drop!(source, vm); + defer_drop!(globals, vm); + defer_drop!(locals, vm); + defer_drop!(owner, vm); + let globals_first = matches!(globals_first, Value::Bool(true)); + let forward_ref = matches!(forward_ref, Value::Bool(true)); + let missing = match missing { + Value::Int(0) => MissingNames::Raise, + Value::Int(every_name) => MissingNames::ForwardRef { + owner: owner.clone_with_heap(vm), + is_class: matches!(is_class, Value::Bool(true)), + every_name: every_name == 2, + }, + _ => unreachable!("frozen code passes the name mode as an int"), + }; + eval_exec::eval_hint( + source, + globals.ref_id(), + locals.ref_id(), + globals_first, + forward_ref, + missing, + vm, + ) +} diff --git a/crates/bashkit-monty/src/modules/unicodedata.rs b/crates/bashkit-monty/src/modules/unicodedata.rs index cc427e7b6..4ee7f3b80 100644 --- a/crates/bashkit-monty/src/modules/unicodedata.rs +++ b/crates/bashkit-monty/src/modules/unicodedata.rs @@ -139,7 +139,7 @@ fn uni_name(vm: &mut VM<'_>, args: ArgValues) -> RunResult { fn uni_lookup(vm: &mut VM<'_>, args: ArgValues) -> RunResult { let value = args.get_one_arg("lookup", vm.heap)?; defer_drop!(value, vm); - let name = value.to_str(vm)?; + let name = value.try_to_str(vm)?; match unicode_names2::character(name) { Some(c) => Ok(allocate_string(c.to_string(), vm.heap)), None => Err(SimpleException::new_msg(ExcType::KeyError, format!("undefined character name '{name}'")).into()), @@ -293,13 +293,12 @@ fn single_char(value: &Value, fn_name: &str, arg_num: Option, vm: &VM<'_>) Some(n) => format!("argument {n}"), None => "argument".to_string(), }; - if !value.is_str(vm.heap) { - return Err(ExcType::type_error(format!( + let s = value.as_str(vm).ok_or_else(|| { + ExcType::type_error(format!( "{fn_name}() {arg_word} must be a unicode character, not {}", value.py_type_name(vm) - ))); - } - let s = value.to_str(vm)?; + )) + })?; let mut chars = s.chars(); match (chars.next(), chars.next()) { (Some(c), None) => Ok(c), diff --git a/crates/bashkit-monty/src/object_bridge.rs b/crates/bashkit-monty/src/object_bridge.rs index 36faf8cae..a8a7277aa 100644 --- a/crates/bashkit-monty/src/object_bridge.rs +++ b/crates/bashkit-monty/src/object_bridge.rs @@ -20,7 +20,7 @@ use crate::{ builtins::Builtins, bytecode::VM, defer_drop, - exception_private::{RunError, SimpleException}, + exception_private::{RunError, RunResult, SimpleException}, heap::{DropGuard, DropWithContext, Heap, HeapData, HeapId, HeapReadOutput}, modules::dataclasses, types::{ @@ -47,8 +47,10 @@ use crate::{ /// [`MontyGraphExt::to_values`] directly so their values share one arena. pub(crate) trait MontyObjectExt: Sized { /// Exports a `Value` into its own arena, taking ownership of the `Value` - /// and dropping it via `drop_with`. - fn export(value: Value, vm: &mut VM<'_>) -> Self; + /// and dropping it via `drop_with`. Fails only with a resource limit hit + /// during export, where a user `__repr__` can run (see [`GraphExporter::finish`]); + /// callers outside the run loop wrap it in [`VM::export_on_clock`]. + fn export(value: Value, vm: &mut VM<'_>) -> RunResult; /// Imports this value into the heap. Fails with `InvalidInputError` on /// output-only nodes (`Repr`, `Cycle`), on a sandbox class or instance @@ -58,10 +60,11 @@ pub(crate) trait MontyObjectExt: Sized { } impl MontyObjectExt for MontyObject { - fn export(value: Value, vm: &mut VM<'_>) -> Self { + fn export(value: Value, vm: &mut VM<'_>) -> RunResult { let mut exporter = GraphExporter::new(); let root = exporter.push_owned(value, vm); - unstable::object_from_graph(exporter.finish(vm), root).expect("exported root is valid") + let graph = exporter.finish(vm)?; + Ok(unstable::object_from_graph(graph, root).expect("exported root is valid")) } fn to_value(self, vm: &mut VM<'_>) -> Result { @@ -120,9 +123,12 @@ pub(crate) struct GraphExporter { /// [`MontyNode::Cycle`] leaf rather than infinite recursion. in_progress: AHashSet, /// A reference to every memoized object, released by [`finish`](Self::finish): - /// a user `__repr__` run by [`repr_node`] can free an exported object + /// a user `__repr__` run by [`repr_node`](Self::repr_node) can free an exported object /// mid-message, and a new object in the reused slot would inherit its node. pinned: Vec, + /// The first uncatchable error (a resource limit) raised by a user + /// `__repr__`; once set no more user code runs and `finish` returns it. + error: Option, } impl GraphExporter { @@ -132,6 +138,7 @@ impl GraphExporter { memo: AHashMap::new(), in_progress: AHashSet::new(), pinned: Vec::new(), + error: None, } } @@ -148,9 +155,15 @@ impl GraphExporter { } /// The finished arena, releasing the pins on the memoized objects. - pub(crate) fn finish(self, vm: &mut VM<'_>) -> MontyGraph { + /// + /// Fails with the uncatchable error a user `__repr__` raised during export, + /// so a resource limit ends the run rather than becoming a repr string. + pub(crate) fn finish(self, vm: &mut VM<'_>) -> RunResult { self.pinned.drop_with(vm); - self.graph + match self.error { + Some(err) => Err(err), + None => Ok(self.graph), + } } /// Records `id`'s node in the memo and pins the object until `finish`. @@ -163,6 +176,10 @@ impl GraphExporter { /// Exports a borrowed value and returns its node. Non-`Ref` values need /// only the interner; heap objects go through [`push_ref`](Self::push_ref). pub(crate) fn push(&mut self, value: &Value, vm: &mut VM<'_>) -> NodeId { + // `finish` discards the graph after an uncatchable error, so skip the rest of the walk. + if self.error.is_some() { + return self.push_node(MontyNode::Repr(String::new())); + } // Check depth limit before processing let Ok(mut guard) = vm.recursion_guard() else { return self.push_node(MontyNode::Repr("".to_owned())); @@ -179,19 +196,19 @@ impl GraphExporter { Value::Int(i) => MontyNode::Int(*i), Value::Float(f) => MontyNode::Float(*f), Value::InternString(string_id) => MontyNode::String(interns.get_str(*string_id).to_owned()), + Value::InlineString(text) => MontyNode::String(text.as_str().to_owned()), Value::InternBytes(bytes_id) => MontyNode::Bytes(interns.get_bytes(*bytes_id).to_owned()), Value::InternLongInt(li_id) => MontyNode::BigInt(interns.get_long_int(*li_id).clone()), Value::Ref(id) => return self.push_ref(*id, value, vm), - Value::Builtin(Builtins::Type(Type::Instance(class_id))) => return self.sandbox_class_node(*class_id, vm), - Value::Builtin(Builtins::Type(t)) => match MontyType::from_internal_static(*t) { + Value::Builtin(Builtins::Type(t)) => match MontyType::from_internal_static(Type::from(*t)) { Some(ty) => MontyNode::Type(ty), - None => repr_node(value, vm), + None => self.repr_node(value, vm), }, Value::Builtin(Builtins::ExcType(e)) => MontyNode::Type(MontyType::Exception(*e)), Value::Builtin(Builtins::Function(f)) => MontyNode::BuiltinFunction(*f), #[cfg(feature = "memory-model-checks")] Value::Dereferenced => panic!("Dereferenced found while exporting a value"), - _ => repr_node(value, vm), + _ => self.repr_node(value, vm), }; self.push_node(node) } @@ -239,7 +256,7 @@ impl GraphExporter { } /// Converts one heap object into its node, pushing container children first. - /// Recursing can run a user `__repr__` ([`repr_node`] on e.g. a + /// Recursing can run a user `__repr__` ([`repr_node`](Self::repr_node) on e.g. a /// `functools.partial` bound to an instance), so mutable containers clone /// every child before recursing: the clones keep the children alive and the /// iteration valid if that `__repr__` mutates the container. Immutable @@ -350,7 +367,7 @@ impl GraphExporter { } HeapReadOutput::DateTime(dt) => match datetime_type::to_monty_datetime(dt.get(vm.heap)) { Some(datetime) => MontyNode::DateTime(datetime), - None => repr_node(value, vm), + None => self.repr_node(value, vm), }, HeapReadOutput::Time(t) => { let time = t.get(vm.heap); @@ -451,10 +468,10 @@ impl GraphExporter { imag: c.imag, }) } - // A host module crosses back with its id and attrs; a bundled one - // has no host identity and crosses as its repr. - HeapReadOutput::Module(m) => match m.get(vm.heap).id() { - Some(id) => { + // A host module crosses back with its id and attrs; a bundled or + // file one has no host identity and crosses as its repr. + HeapReadOutput::Module(m) => { + if let Some(id) = m.get(vm.heap).id() { let name = m.get(vm.heap).name_str(vm.interns).to_owned(); let children = snapshot_dict_pairs(m.get(vm.heap).attrs(), vm.heap); defer_drop!(children, vm); @@ -463,9 +480,10 @@ impl GraphExporter { id, attrs: self.push_pairs(children, vm), } + } else { + MontyNode::Repr(m.get(vm.heap).repr(vm.interns)) } - None => MontyNode::Repr(format!("", m.get(vm.heap).name_str(vm.interns))), - }, + } HeapReadOutput::Coroutine(coro) => { let func_id = coro.get(vm.heap).func_id; let func = vm.interns.get_function(func_id); @@ -491,7 +509,37 @@ impl GraphExporter { name: function.get(vm.heap).as_str().to_owned(), docstring: None, }, - _ => repr_node(value, vm), + _ => self.repr_node(value, vm), + } + } + + /// Converts a value to its repr node, falling back to a descriptive error + /// message if `py_repr` fails (e.g. INT_MAX_STR_DIGITS). An uncatchable + /// error is stashed for [`finish`](Self::finish) instead, and after one no + /// further `__repr__` runs. + fn repr_node(&mut self, value: &Value, vm: &mut VM<'_>) -> MontyNode { + if self.error.is_some() { + MontyNode::Repr(String::new()) + } else { + match value.py_repr(vm) { + Ok(s) => { + // `py_repr` yields a heap `str` `Value`; extract its text and drop it. + defer_drop!(s, vm); + MontyNode::Repr(s.try_to_str(vm).map(str::to_owned).unwrap_or_default()) + } + Err(err @ RunError::UncatchableExc(_)) => { + self.error = Some(err); + MontyNode::Repr(String::new()) + } + Err(RunError::Internal(msg)) => { + let ty = value.py_type_name(vm); + MontyNode::Repr(format!("<{ty} object, error on repr(): {msg}>")) + } + Err(RunError::Exc(exc)) => { + let ty = value.py_type_name(vm); + MontyNode::Repr(format!("<{ty} object, error on repr(): {}>", exc.exc)) + } + } } } @@ -786,7 +834,8 @@ impl MontyTypeExt for MontyType { | Type::CsvDialect | Type::DecimalContext | Type::DecimalSignalDict - | Type::DecimalContextManager => return None, + | Type::DecimalContextManager + | Type::ForwardRef => return None, Type::Decimal => Self::Decimal, Type::Tuple => Self::Tuple, Type::NamedTuple => Self::NamedTuple, @@ -1054,7 +1103,9 @@ fn import_node( let file = OpenFile::with_state(handle.path, handle.mode, handle.position); Ok(Value::Ref(vm.heap.allocate(HeapData::OpenFile(Box::new(file))))) } - MontyNode::Type(t) => Ok(Value::Builtin(Builtins::Type(t.to_internal()))), + MontyNode::Type(t) => Ok(Value::Builtin(Builtins::Type( + t.to_internal().try_into().expect("host types are static"), + ))), MontyNode::BuiltinFunction(f) => Ok(Value::Builtin(Builtins::Function(f))), MontyNode::Function { name, .. } => Ok(vm.heap.get_ext_function(&name)), MontyNode::Repr(_) => Err(InvalidInputError::invalid_type("'Repr' is not a valid input value")), @@ -1139,23 +1190,3 @@ fn snapshot_dict_pairs(dict: &Dict, heap: &Heap) -> Vec<(Value, Value)> { .map(|(key, value)| (key.clone_with_heap(heap), value.clone_with_heap(heap))) .collect() } - -/// Converts a value to its repr node, falling back to a descriptive error -/// message if `py_repr` fails (e.g. INT_MAX_STR_DIGITS). -fn repr_node(value: &Value, vm: &mut VM<'_>) -> MontyNode { - match value.py_repr(vm) { - Ok(s) => { - // `py_repr` yields a heap `str` `Value`; extract its text and drop it. - defer_drop!(s, vm); - MontyNode::Repr(s.to_str(vm).map(str::to_owned).unwrap_or_default()) - } - Err(e) => { - let ty = value.py_type_name(vm); - let msg = match &e { - RunError::Internal(s) => s.to_string(), - RunError::Exc(exc) | RunError::UncatchableExc(exc) => exc.exc.to_string(), - }; - MontyNode::Repr(format!("<{ty} object, error on repr(): {msg}>")) - } - } -} diff --git a/crates/bashkit-monty/src/os_dispatch.rs b/crates/bashkit-monty/src/os_dispatch.rs index 3f9bf279b..8b37da16d 100644 --- a/crates/bashkit-monty/src/os_dispatch.rs +++ b/crates/bashkit-monty/src/os_dispatch.rs @@ -30,7 +30,7 @@ use monty_types::{ use crate::{ args::{ArgValues, FromArgs, LaxBool}, - bytecode::{CallResult, VM}, + bytecode::{CallResult, PendingImport, VM}, defer_drop, exception_private::{ExcTypeExt, RunError, RunResult, SimpleException}, heap::{ContainsHeap, DropWithContext, Heap, HeapData, HeapId}, @@ -77,6 +77,8 @@ pub(crate) enum PendingEffect { /// Builds a walk, scandir or glob result from a `Path.scan` reply — or /// from the `OSError` it answered with (see [`ScanEffect::absorbs`]). Scan(ScanEffect), + /// Resolves an `import` call's answer: a module, a file to run, or a miss. + Import(PendingImport), } impl PendingEffect { @@ -87,6 +89,7 @@ impl PendingEffect { match self { Self::Pre(effect) => Some(effect.operation_name()), Self::Scan(effect) => Some(effect.operation_name()), + Self::Import(_) => Some("import"), Self::Post(PostConversionEffect::OpenName { .. }) => Some("open"), // The parse answers the `json.load` call; a future would hand Python the text. Self::Post(PostConversionEffect::JsonLoad { .. }) => Some("json.load"), @@ -116,7 +119,7 @@ impl PendingEffect { /// held across the host yield (see [`PostConversionEffect::release`]). pub(crate) fn release(self, heap: &mut impl ContainsHeap) { match self { - Self::Pre(_) => {} + Self::Pre(_) | Self::Import(_) => {} Self::Post(effect) => effect.release(heap), Self::Scan(effect) => effect.release(heap), } @@ -438,14 +441,31 @@ pub(crate) fn release_pending_effect(effect: Option, heap: &mut i } } +/// The error CPython raises for `call`'s paths as the user wrote them, before any I/O: +/// `ValueError` for a NUL byte, else `FileNotFoundError` for `''`. +/// +/// Must run before [`resolve_call_paths`], which would turn `''` into the working directory. +pub(crate) fn check_raw_call_paths(call: &OsFunctionCall) -> RunResult<()> { + if let Err(message) = call.check_path_null_bytes() { + Err(ExcType::value_error(message)) + } else if call.has_empty_path() { + Err(match (call.fs_primary_path(), call.rename_destination()) { + (Some(src), Some(dst)) => ExcType::file_not_found_error_pair(src, dst), + (path, _) => ExcType::file_not_found_error(path.unwrap_or_default()), + }) + } else { + Ok(()) + } +} + /// Resolves every relative path in `call` against `cwd` (see [`posix_join`]). /// -/// Runs at the VM's single OS-call exit, so builtins and `Path` methods can -/// hand over paths exactly as the user wrote them. Absolute and empty paths -/// are left untouched, not copied. +/// Runs at the VM's single OS-call exit, after [`check_raw_call_paths`] has +/// rejected `''`, so builtins and `Path` methods can hand over paths exactly as +/// the user wrote them. Absolute paths are left untouched, not copied. pub(crate) fn resolve_call_paths(call: &mut OsFunctionCall, cwd: &str) { for path in call.fs_paths_mut() { - if !path.is_empty() && !path.starts_with('/') { + if !path.starts_with('/') { *path = MontyPath::new(posix_join(cwd, path)); } } @@ -697,7 +717,7 @@ fn extract_str_data( ) -> RunResult { let data = arg_or_missing_data(method, args, heap)?; // Only `str`: a path-like is not text, so CPython refuses `Path` and `DirEntry` here. - let data_str = data.to_str_heap(heap, interns).ok().map(str::to_owned); + let data_str = data.try_to_str_heap(heap, interns).ok().map(str::to_owned); // CPython names the type by its `__name__`: no module (`DirEntry`, not // `posix.DirEntry`), but a class's own name (`Point` for a named tuple). @@ -868,11 +888,13 @@ pub(crate) fn value_to_owned_string(value: &Value, heap: &Heap, interns: &Intern /// The text of a `str`, `Path` or `DirEntry` `value`, borrowed, else `None`: /// what [`value_to_owned_string`] copies, for sizing the copy first. -pub(crate) fn value_as_path_str<'a>(value: &Value, heap: &'a Heap, interns: &'a Interns) -> Option<&'a str> { +pub(crate) fn value_as_path_str<'a>(value: &'a Value, heap: &'a Heap, interns: &'a Interns) -> Option<&'a str> { + if let Some(text) = value.as_str_heap(heap, interns) { + return Some(text); + } + match value { - Value::InternString(id) => Some(interns.get_str(*id)), Value::Ref(id) => match heap.get(*id) { - HeapData::Str(s) => Some(s.as_str()), HeapData::Path(p) => Some(p.as_str()), HeapData::DirScan(scan) => scan.fspath(), _ => None, @@ -883,10 +905,15 @@ pub(crate) fn value_as_path_str<'a>(value: &Value, heap: &'a Heap, interns: &'a /// Owned `Vec` if `value` is a `bytes` (interned or heap), else `None`. pub(crate) fn value_to_owned_bytes(value: &Value, heap: &Heap, interns: &Interns) -> Option> { + value_as_bytes(value, heap, interns).map(<[u8]>::to_vec) +} + +/// The bytes of a `bytes` `value` (interned or heap), borrowed, else `None`. +pub(crate) fn value_as_bytes<'a>(value: &Value, heap: &'a Heap, interns: &'a Interns) -> Option<&'a [u8]> { match value { - Value::InternBytes(id) => Some(interns.get_bytes(*id).to_owned()), + Value::InternBytes(id) => Some(interns.get_bytes(*id)), Value::Ref(id) => match heap.get(*id) { - HeapData::Bytes(b) => Some(b.as_slice().to_owned()), + HeapData::Bytes(b) => Some(b.as_slice()), _ => None, }, _ => None, diff --git a/crates/bashkit-monty/src/parse.rs b/crates/bashkit-monty/src/parse.rs index 05442fdc6..941e90cb7 100644 --- a/crates/bashkit-monty/src/parse.rs +++ b/crates/bashkit-monty/src/parse.rs @@ -12,12 +12,12 @@ use ruff_python_ast::{ token::TokenKind, visitor::{Visitor, walk_expr}, }; -use ruff_python_parser::{Mode, parse_expression, parse_module}; +use ruff_python_parser::{Mode, parse_expression_range, parse_module}; use ruff_text_size::{Ranged, TextRange, TextSize}; use crate::{ args::{ArgExprs, CallArg, CallKwarg, Kwarg}, - exception_private::{ExcType, ExcTypeExt, RunError, SimpleException}, + exception_private::{ExcType, ExcTypeExt, ExceptionRaise, RunError, SimpleException}, expressions::{ AssignTarget, Callable, CmpOperator, Comprehension, DictItem, Expr, ExprLoc, Identifier, ImportName, Literal, MatchCase, Node, Operator, Pattern, SequenceItem, Submodule, UnpackTarget, @@ -49,12 +49,11 @@ pub const MAX_NESTING_DEPTH: u16 = 30; /// Caps dotted-import components to bound quadratic storage for interned path prefixes. pub const MAX_IMPORT_COMPONENTS: usize = 32; -/// `from __future__ import ...` features whose semantics Monty already provides, -/// so importing them is a no-op rather than an error. +/// `from __future__ import ...` features Monty accepts. /// /// All but the last are inert in CPython too, having become mandatory by 3.7. -/// `annotations` is still meaningful there, and a no-op here only because Monty -/// stringizes unconditionally (see `limitations/typing.md`) — what it asks for. +/// `annotations` binds nothing either, but is recorded on the module's code so +/// `typing.get_type_hints()` applies PEP 563's namespace rules. const SUPPORTED_FUTURES: [&str; 9] = [ "nested_scopes", "generators", @@ -148,6 +147,12 @@ pub struct RawFunctionDef { pub body: Vec, /// Whether this is an async function (`async def`). pub is_async: bool, + /// The `__annotate__(format)` function of an annotated `def` (PEP 649), built by + /// [`Parser::synthesize_annotate`]; `None` when nothing is annotated. + pub annotate: Option>, + /// Whether this is a synthesized `__annotate__`: every name but the `format` + /// parameter resolves by name at run time and nothing is captured as a cell. + pub is_annotate: bool, } /// Type alias for parsed AST nodes (output of the parser). @@ -198,29 +203,40 @@ fn code_range(filename: StringId, range: TextRange) -> CodeRange { } } +/// A parsed module body. +pub(crate) struct ParsedModule { + pub nodes: Vec, + /// Whether the module runs under `from __future__ import annotations`, + /// inherited or imported; the compiler stamps it on every `Code`. + pub future_annotations: bool, +} + /// Parses code into a private interner overlay, discarded if any compilation stage fails. +/// `future_annotations` is the flag inherited from an earlier REPL feed. pub(crate) fn parse_with_interner( code: &str, filename: &str, interner: &mut CompileInterns<'_>, -) -> Result, ParseError> { + future_annotations: bool, +) -> Result { // Interned up front so a syntax error can be located without a `Parser`, // leaving the parser to be built once, fully populated, after parsing. let filename_id = interner.intern(filename); // Module sources are scanned for nesting by their entry points // (`MontyRun::new`, the REPL feeds), not here. - parse_module_with_filename_id(code, filename_id, interner, usize::MAX) + parse_module_with_filename_id(code, filename_id, interner, usize::MAX, future_annotations) } /// [`parse_with_interner`] for a filename already interned — an `exec()` /// snippet, whose `` id is fresh per call so tracebacks can tell the -/// snippets apart. +/// snippets apart, and which inherits its caller's `future_annotations`. pub(crate) fn parse_module_with_filename_id( code: &str, filename_id: StringId, interner: &mut CompileInterns<'_>, source_scan_threshold: usize, -) -> Result, ParseError> { + future_annotations: bool, +) -> Result { check_source_nesting(code, Mode::Module, filename_id, source_scan_threshold)?; let parsed = parse_module(code).map_err(|e| ParseError::syntax(e.error.to_string(), code_range(filename_id, e.range())))?; @@ -231,12 +247,19 @@ pub(crate) fn parse_module_with_filename_id( .filter(|token| token.kind() == TokenKind::Class) .map(Ranged::start) .collect(); - let mut parser = Parser::new(code, filename_id, interner, class_keyword_offsets); - parser.parse_statements(parsed.into_syntax().body) + let mut parser = Parser::new(code, filename_id, interner, class_keyword_offsets, future_annotations); + let nodes = parser.parse_statements(parsed.into_syntax().body)?; + Ok(ParsedModule { + nodes, + future_annotations: parser.future_annotations, + }) } /// Parses `code` as a single expression, as `eval()` does. /// +/// Leading spaces and tabs are skipped, as CPython's `eval()` strips them, but +/// parsing starts at that offset in the full source so every position in the +/// result and in any error stays relative to what the caller passed. /// `filename_id` is the snippet's fresh `` id (see /// [`parse_module_with_filename_id`]). pub(crate) fn parse_expression_with_interner( @@ -246,13 +269,62 @@ pub(crate) fn parse_expression_with_interner( source_scan_threshold: usize, ) -> Result { check_source_nesting(code, Mode::Expression, filename_id, source_scan_threshold)?; - let parsed = parse_expression(code) + // ruff's lexer asserts the same `u32` bound on every source it parses. + let end = TextSize::try_from(code.len()).expect("eval source exceeds u32 offsets"); + let start = end - TextSize::of(code.trim_start_matches([' ', '\t'])); + reject_leading_bom(code, start, filename_id)?; + let parsed = parse_expression_range(code, TextRange::new(start, end)) .map_err(|e| ParseError::syntax(e.error.to_string(), code_range(filename_id, e.range())))?; + if let Some(range) = trailing_indent(code) { + return Err(ParseError::syntax( + "Unexpected indentation", + code_range(filename_id, range), + )); + } // No `class` keywords can occur in a bare expression. - let mut parser = Parser::new(code, filename_id, interner, Vec::new()); + // An expression holds no annotations, so the `__future__` state is moot. + let mut parser = Parser::new(code, filename_id, interner, Vec::new(), false); parser.parse_expression(*parsed.into_syntax().body) } +/// Rejects a byte-order mark at `start`, where an `eval()` or `exec()` snippet's +/// code begins, with CPython's `SyntaxError`. +/// +/// ruff skips a BOM at offset 0, which suits a module read from a file, but +/// CPython treats one in a `str` snippet as an invalid character. +pub(crate) fn reject_leading_bom(code: &str, start: TextSize, filename_id: StringId) -> Result<(), ParseError> { + if code[start.to_usize()..].starts_with('\u{feff}') { + Err(ParseError::syntax( + "invalid non-printable character U+FEFF", + code_range(filename_id, TextRange::at(start, TextSize::of('\u{feff}'))), + )) + } else { + Ok(()) + } +} + +/// The last line of an `eval()` source when it holds only indentation, which +/// CPython's tokenizer rejects as an unexpected indent but ruff accepts. +/// +/// A final line with no newline after it is not blank to CPython, so its +/// indentation counts. A form feed resets the column, as in CPython, and a line +/// continued by a backslash is not a new line at all. +fn trailing_indent(code: &str) -> Option { + let line_start = code.rfind(['\n', '\r'])? + 1; + let line = &code[line_start..]; + let column = line.chars().try_fold(0usize, |column, c| match c { + ' ' => Some(column + 1), + '\t' => Some(column / 8 * 8 + 8), + '\x0c' => Some(0), + _ => None, + })?; + let continued = code[..line_start].trim_end_matches(['\n', '\r']).ends_with('\\'); + (column > 0 && !continued).then(|| { + let start = TextSize::try_from(line_start).expect("eval source exceeds u32 offsets"); + TextRange::at(start, TextSize::of(line)) + }) +} + /// [`check_source_nesting`] for a host vetting a snippet before compiling it, /// producing the `SyntaxError` the compile would raise. pub(crate) fn source_nesting_exception( @@ -333,6 +405,12 @@ pub struct Parser<'a, 'i> { /// class's traceback frame needs the concrete position. Read only by /// [`Parser::class_keyword_range`]. class_keyword_offsets: Vec, + /// Whether the module runs under `from __future__ import annotations`: + /// inherited by an `exec()` snippet or REPL feed, or set by the import. + future_annotations: bool, + /// Whether a `__future__` import may still appear: only a docstring and + /// other `__future__` imports precede one, at module level. + future_allowed: bool, } impl<'a, 'i> Parser<'a, 'i> { @@ -341,6 +419,7 @@ impl<'a, 'i> Parser<'a, 'i> { filename_id: StringId, interner: &'a mut CompileInterns<'i>, class_keyword_offsets: Vec, + future_annotations: bool, ) -> Self { Self { code, @@ -348,6 +427,8 @@ impl<'a, 'i> Parser<'a, 'i> { interner, depth_remaining: MAX_NESTING_DEPTH, class_keyword_offsets, + future_annotations, + future_allowed: true, } } @@ -366,7 +447,12 @@ impl<'a, 'i> Parser<'a, 'i> { // pass either `Vec` or ruff's `ThinVec` without an intermediate copy. let iter = statements.into_iter(); let mut out = Vec::with_capacity(iter.len()); - for stmt in iter { + for (index, stmt) in iter.enumerate() { + // Any other statement, including one whose body this is, ends the + // stretch of the file where `__future__` imports are allowed. + if self.future_allowed && !(is_future_import(&stmt) || (index == 0 && is_docstring(&stmt))) { + self.future_allowed = false; + } out.push(self.parse_statement(stmt)?); } Ok(out) @@ -688,10 +774,18 @@ impl<'a, 'i> Parser<'a, 'i> { }), } } - Stmt::AnnAssign(ast::StmtAnnAssign { target, value, .. }) => match value { - Some(value) => self.parse_assignment(*target, *value), - None => Ok(Node::Pass), - }, + Stmt::AnnAssign(ast::StmtAnnAssign { + target, + annotation, + value, + .. + }) => { + self.check_annotation(&annotation)?; + match value { + Some(value) => self.parse_assignment(*target, *value), + None => Ok(Node::Pass), + } + } Stmt::For(ast::StmtFor { is_async, target, @@ -800,13 +894,16 @@ impl<'a, 'i> Parser<'a, 'i> { Ok(node) } Stmt::Match(m) => self.parse_match(m), - Stmt::Raise(ast::StmtRaise { exc, .. }) => { - // TODO add cause to Node::Raise - let expr = match exc { + Stmt::Raise(ast::StmtRaise { exc, cause, .. }) => { + let exc = match exc { Some(expr) => Some(self.parse_expression(*expr)?), None => None, }; - Ok(Node::Raise(expr)) + let cause = match cause { + Some(expr) => Some(self.parse_expression(*expr)?), + None => None, + }; + Ok(Node::Raise { exc, cause }) } Stmt::Try(ast::StmtTry { body, @@ -885,6 +982,12 @@ impl<'a, 'i> Parser<'a, 'i> { // what it says. `level == 0` keeps `from .__future__ import x` an // ordinary relative import, falling through to the `ImportError`. if level == 0 && module.as_ref().is_some_and(|m| m.as_str() == "__future__") { + if !self.future_allowed { + return Err(ParseError::syntax( + "from __future__ imports must occur at the beginning of the file", + position, + )); + } return match names .iter() .find(|a| a.asname.is_some() || !SUPPORTED_FUTURES.contains(&a.name.id.as_str())) @@ -910,10 +1013,17 @@ impl<'a, 'i> Parser<'a, 'i> { "aliasing a `__future__` feature", self.convert_range(alias.range), )), - None => Ok(Node::Pass), + None => { + if names.iter().any(|a| a.name.id.as_str() == "annotations") { + self.future_annotations = true; + } + Ok(Node::Pass) + } }; } // We only support absolute imports (level 0) + // TODO(site-packages): relative imports in modules imported from files, + // resolved against the importing module's `__package__`. if level != 0 { return Err(ParseError::import_error( "attempted relative import with no known parent package", @@ -1000,9 +1110,10 @@ impl<'a, 'i> Parser<'a, 'i> { /// before calling here, so it always receives an empty list. fn parse_function_def( &mut self, - function: ast::StmtFunctionDef, + mut function: ast::StmtFunctionDef, ) -> Result<(RawFunctionDef, Vec), ParseError> { let decorators = self.parse_decorators(function.decorator_list)?; + let annotations = self.take_function_annotations(&mut function.parameters, function.returns.take()); let params = &function.parameters; @@ -1030,6 +1141,16 @@ impl<'a, 'i> Parser<'a, 'i> { }; let name = self.identifier(&function.name.id, function.name.range); + let annotate = if annotations.is_empty() { + None + } else { + let annotate_id = self.interner.intern("__annotate__"); + Some(Box::new(self.synthesize_annotate( + annotations, + annotate_id, + name.position, + )?)) + }; // Parse function body recursively let body = self.parse_statements(function.body)?; let is_async = function.is_async; @@ -1040,11 +1161,131 @@ impl<'a, 'i> Parser<'a, 'i> { signature, body, is_async, + annotate, + is_annotate: false, }, decorators, )) } + /// Takes a `def`'s parameter and return annotations out of the signature, in + /// the order CPython stores them: regular parameters before positional-only + /// ones, then `*args`, keyword-only, `**kwargs` and `return`. + fn take_function_annotations( + &mut self, + params: &mut ast::Parameters, + returns: Option>, + ) -> Vec<(StringId, Box)> { + let ast::Parameters { + posonlyargs, + args, + vararg, + kwonlyargs, + kwarg, + .. + } = params; + let mut annotations: Vec<(StringId, Box)> = args + .iter_mut() + .chain(posonlyargs.iter_mut()) + .map(|p| &mut p.parameter) + .chain(vararg.as_deref_mut()) + .chain(kwonlyargs.iter_mut().map(|p| &mut p.parameter)) + .chain(kwarg.as_deref_mut()) + .filter_map(|p| Some((self.interner.intern(&p.name.id), p.annotation.take()?))) + .collect(); + if let Some(returns) = returns { + annotations.push((self.interner.intern("return"), returns)); + } + annotations + } + + /// Builds the `__annotate__(format)` function CPython's compiler emits for an + /// annotated `def` or class body (PEP 649): + /// + /// ```python test="skip" + /// def __annotate__(format): + /// if format > 2: + /// raise NotImplementedError + /// return {'x': , ...} + /// ``` + /// + /// Under `from __future__ import annotations` the dict holds the stringized + /// text instead, so `__annotations__` reads as PEP 563 strings. + fn synthesize_annotate( + &mut self, + annotations: Vec<(StringId, Box)>, + name_id: StringId, + position: CodeRange, + ) -> Result { + let items = self.annotation_items(annotations, position)?; + let format_id = self.interner.intern("format"); + let name = |parser: &mut Self, text: &str| { + let id = parser.interner.intern(text); + ExprLoc::new(position, Expr::Name(Identifier::new(id, position))) + }; + let test = ExprLoc::new( + position, + Expr::CmpOp { + left: Box::new(name(self, "format")), + op: CmpOperator::Gt, + right: Box::new(ExprLoc::new(position, Expr::Literal(Literal::Int(2)))), + }, + ); + let raise = Node::Raise { + exc: Some(name(self, "NotImplementedError")), + cause: None, + }; + let body = vec![ + Node::If { + test, + body: vec![raise], + or_else: Vec::new(), + }, + Node::Return(Some(ExprLoc::new(position, Expr::Dict(items)))), + ]; + Ok(RawFunctionDef { + name: Identifier::new(name_id, position), + signature: ParsedSignature { + args: vec![ParsedParam { + name: format_id, + default: None, + }], + ..ParsedSignature::default() + }, + body, + is_async: false, + annotate: None, + is_annotate: true, + }) + } + + /// The `'name': annotation` pairs of an `__annotations__` dict: each + /// annotation parsed as an expression, or under `from __future__ import + /// annotations` stringized to the text CPython would store. + /// + /// A stringized annotation never reaches [`Parser::parse_expression`], so + /// the depth check guarding stringization's recursive passes is made here. + fn annotation_items( + &mut self, + annotations: Vec<(StringId, Box)>, + position: CodeRange, + ) -> Result, ParseError> { + let mut items = Vec::with_capacity(annotations.len()); + for (name, mut annotation) in annotations { + self.check_annotation(&annotation)?; + let key = ExprLoc::new(position, Expr::Literal(Literal::Str(name))); + let value = if self.future_annotations { + let range = self.convert_range(annotation.range()); + let text_id = self.interner.intern(&stringize_annotation(&mut annotation)); + ExprLoc::new(range, Expr::Literal(Literal::Str(text_id))) + } else { + self.parse_expression(*annotation)? + }; + items.push(DictItem::Pair(key, value)); + } + Ok(items) + } + /// Parses decorator expressions in source order. /// /// They are ordinary expressions evaluated in the enclosing scope; the @@ -1072,7 +1313,7 @@ impl<'a, 'i> Parser<'a, 'i> { /// recorded in `members`, in source order, for namespace assembly. /// /// `pass` and `...` are ignored; a leading docstring becomes a `__doc__` - /// member, and annotated names a stringized `__annotations__`. Class + /// member, and annotated names the class's `__annotate__` function. Class /// decorators are supported (enclosing scope, applied bottom-up); /// inheritance, function/method decorators, and anything else in the body /// are rejected as not-implemented, reserving the syntax for later. @@ -1098,9 +1339,10 @@ impl<'a, 'i> Parser<'a, 'i> { // namespace dict from the body's locals. let mut body = Vec::new(); let mut members = Vec::new(); - // `(name, "source text")` pairs assembled into `__annotations__` below; - // always stringized (PEP 563). See `limitations/typing.md`. - let mut annotations: Vec = Vec::new(); + // `(name, annotation)` pairs, compiled into the class's `__annotate__` + // below (or, under `from __future__ import annotations`, stringized + // into `__annotations__`). + let mut annotations: Vec<(StringId, Box)> = Vec::new(); // CPython stores the class docstring as a real `__doc__` entry in the // class dict (`None` when absent), so synthesize a `__doc__ = Parser<'a, 'i> { self.parse_class_var(ident, *value, &mut members, &mut body)?; } // `name: T [= ]` — an annotated class-level name. The - // annotation is recorded (stringized) in `__annotations__`; a + // annotation goes into the class's `__annotate__` (see below); a // value additionally makes it a class variable. A bare `name: T` // records the annotation but binds no value (matching CPython). Stmt::AnnAssign(ast::StmtAnnAssign { target, - mut annotation, + annotation, value, range, .. @@ -1173,7 +1415,7 @@ impl<'a, 'i> Parser<'a, 'i> { }) = *target { let ident = self.identifier(&id, name_range); - annotations.push(self.parse_class_annotation(ident, &mut annotation)?); + annotations.push((ident.name_id, annotation)); if let Some(value) = value { self.parse_class_var(ident, *value, &mut members, &mut body)?; } @@ -1224,26 +1466,36 @@ impl<'a, 'i> Parser<'a, 'i> { ); // Last statement so the values are assembled after all members exist. - // Always present (empty dict) to match `Cls.__annotations__ == {}`. - let annotations_target = Identifier::new(self.interner.intern("__annotations__"), position); - let body_binds_annotations = members.iter().any(|m| m.name_id == annotations_target.name_id); - if body_binds_annotations && !annotations.is_empty() { - // Being last, the synthetic assignment would clobber the body's own - // binding and lose these entries. CPython stores into whatever the name - // holds instead — merging into a dict, `TypeError` otherwise. - return Err(ParseError::not_implemented( - "assigning `__annotations__` in a class body with annotated names", - position, - )); - } - // With nothing to store, the body's own binding stands — synthesizing an - // empty dict over it would break class bodies CPython accepts. - if !body_binds_annotations { - members.push(annotations_target); - body.push(Node::Assign { - target: annotations_target, - object: ExprLoc::new(position, Expr::Dict(annotations)), - }); + // CPython's compiler stores the class's `__annotate__` under + // `__annotate_func__`; under `from __future__ import annotations` it + // stores the stringized dict as `__annotations__` instead. + if !annotations.is_empty() { + if self.future_annotations { + let annotations_target = Identifier::new(self.interner.intern("__annotations__"), position); + if members.iter().any(|m| m.name_id == annotations_target.name_id) { + // Being last, the synthetic assignment would clobber the body's own + // binding and lose these entries. CPython stores into whatever the name + // holds instead — merging into a dict, `TypeError` otherwise. + return Err(ParseError::not_implemented( + "assigning `__annotations__` in a class body with annotated names", + position, + )); + } + let items = self.annotation_items(annotations, position)?; + members.push(annotations_target); + body.push(Node::Assign { + target: annotations_target, + object: ExprLoc::new(position, Expr::Dict(items)), + }); + } else { + let annotate_target = Identifier::new(self.interner.intern("__annotate_func__"), position); + let def = self.synthesize_annotate(annotations, annotate_target.name_id, position)?; + members.push(annotate_target); + body.push(Node::FunctionDef { + def, + decorators: Vec::new(), + }); + } } // Wrap the body statements in a synthetic zero-arg function. The class @@ -1255,6 +1507,8 @@ impl<'a, 'i> Parser<'a, 'i> { signature: ParsedSignature::default(), body, is_async: false, + annotate: None, + is_annotate: false, }; Ok(Node::ClassDef { @@ -1298,24 +1552,6 @@ impl<'a, 'i> Parser<'a, 'i> { } } - /// Builds the `'name': 'annotation'` pair for one annotated class-body name. - /// - /// The annotation is stringized rather than evaluated (see - /// `limitations/typing.md`); [`stringize_annotation`] owns rendering it back - /// to the text CPython would store. - /// - /// The annotation never reaches [`Parser::parse_expression`], so the depth - /// check guarding stringization's two recursive passes is made here. - fn parse_class_annotation(&mut self, ident: Identifier, annotation: &mut AstExpr) -> Result { - self.check_expression_depth(annotation)?; - let ann_range = annotation.range(); - let ann_id = self.interner.intern(&stringize_annotation(annotation)); - Ok(DictItem::Pair( - ExprLoc::new(ident.position, Expr::Literal(Literal::Str(ident.name_id))), - ExprLoc::new(self.convert_range(ann_range), Expr::Literal(Literal::Str(ann_id))), - )) - } - /// Parses a class-variable value and records the binding: rejects class-scope /// walrus, parses the value expression, and appends the member / `Assign` pair /// shared by the `Assign` and `AnnAssign` class-body arms. @@ -1356,6 +1592,19 @@ impl<'a, 'i> Parser<'a, 'i> { } } + /// Depth-checks an annotation and rejects what CPython's compiler refuses in + /// one: a walrus, `yield` or `await` evaluated in the annotation's own scope. + fn check_annotation(&self, annotation: &AstExpr) -> Result<(), ParseError> { + self.check_expression_depth(annotation)?; + match forbidden_in_annotation(annotation) { + Some((kind, range)) => Err(ParseError::syntax( + format!("{kind} cannot be used within an annotation"), + self.convert_range(range), + )), + None => Ok(()), + } + } + /// `lhs = rhs` — parses a single-target assignment into the appropriate `Node` variant. /// /// Dispatches on the shape of `lhs` by delegating to `parse_assign_target`, then wraps @@ -2582,6 +2831,17 @@ fn convert_conversion_flag(flag: RuffConversionFlag) -> ConversionFlag { } } +/// Whether `stmt` is a `from __future__ import ...` directive; a relative +/// `from .__future__` is an ordinary import and ends the stretch like any other. +fn is_future_import(stmt: &Stmt) -> bool { + matches!(stmt, Stmt::ImportFrom(ast::StmtImportFrom { module: Some(module), level: 0, .. }) if module.as_str() == "__future__") +} + +/// Whether `stmt` is a bare string literal, the docstring when it comes first. +fn is_docstring(stmt: &Stmt) -> bool { + matches!(stmt, Stmt::Expr(ast::StmtExpr { value, .. }) if matches!(**value, AstExpr::StringLiteral(_))) +} + /// Does `expr` contain a `:=` that binds in the enclosing (class-body) scope? /// /// Like ruff's `any_over_expr`, but scope-aware for lambdas: a walrus inside a @@ -2619,6 +2879,57 @@ fn contains_class_scope_walrus(expr: &AstExpr) -> bool { finder.found } +/// The first expression CPython rejects in an annotation, in source order, as +/// its error's noun and range. Lambda bodies and comprehensions are their own +/// scopes, so only lambda defaults and a comprehension's first iterable are checked. +fn forbidden_in_annotation(annotation: &AstExpr) -> Option<(&'static str, TextRange)> { + /// Expression visitor recording the first forbidden expression. + struct Finder { + found: Option<(&'static str, TextRange)>, + } + impl Finder { + /// Visits a comprehension's first iterable, the only part evaluated in the annotation's scope. + fn visit_first_iter(&mut self, generators: &[ast::Comprehension]) { + if let Some(first) = generators.first() { + self.visit_expr(&first.iter); + } + } + } + impl<'a> Visitor<'a> for Finder { + fn visit_expr(&mut self, expr: &'a AstExpr) { + match expr { + _ if self.found.is_some() => {} + AstExpr::Named(e) => self.found = Some(("named expression", e.range)), + AstExpr::Yield(ast::ExprYield { range, .. }) | AstExpr::YieldFrom(ast::ExprYieldFrom { range, .. }) => { + self.found = Some(("yield expression", *range)); + } + AstExpr::Await(e) => self.found = Some(("await expression", e.range)), + // Defaults are evaluated in the annotation's scope, the body is not. + AstExpr::Lambda(lambda) => { + for param in lambda + .parameters + .iter() + .flat_map(|params| params.iter_non_variadic_params()) + { + if let Some(default) = ¶m.default { + self.visit_expr(default); + } + } + } + AstExpr::ListComp(ast::ExprListComp { generators, .. }) + | AstExpr::SetComp(ast::ExprSetComp { generators, .. }) + | AstExpr::Generator(ast::ExprGenerator { generators, .. }) => self.visit_first_iter(generators), + AstExpr::DictComp(ast::ExprDictComp { generators, .. }) => self.visit_first_iter(generators), + _ => walk_expr(self, expr), + } + } + } + + let mut finder = Finder { found: None }; + finder.visit_expr(annotation); + finder.found +} + /// The CPython error for a `*target` that is not an element of a tuple or list. fn starred_root_target(position: CodeRange) -> ParseError { ParseError::syntax("starred assignment target must be in a list or tuple", position) @@ -2747,19 +3058,6 @@ pub enum ParseError { } impl ParseError { - /// Moves the error `bytes` later in the source, for a parse of a suffix - /// of the caller's text (`eval()` trims leading whitespace) so the line - /// number is counted from the start of what the caller passed. - pub(crate) fn shifted(mut self, bytes: u32) -> Self { - let (Self::Syntax { position, .. } - | Self::NotImplemented { position, .. } - | Self::NotSupported { position, .. } - | Self::Import { position, .. }) = &mut self; - position.start_byte = position.start_byte.saturating_add(bytes); - position.end_byte = position.end_byte.saturating_add(bytes); - self - } - pub(crate) fn not_implemented(msg: impl Into>, position: CodeRange) -> Self { Self::NotImplemented { msg: msg.into(), @@ -2812,32 +3110,46 @@ impl ParseError { } } + /// Converts an imported file's compile error: the file is the innermost + /// traceback frame, under an `import` line shown without carets, as CPython does. + pub(crate) fn into_file_run_error(self, path: &str, source: &str) -> RunError { + let (exc_type, msg, frame) = self.into_parts(path, source); + RunError::Exc(ExceptionRaise { + exc: SimpleException::new_msg(exc_type, msg), + frame: None, + snippet_frame: Some(Box::new(frame)), + hide_caret: true, + }) + } + pub fn into_python_exc(self, filename: &str, source: &str) -> MontyException { + let (exc_type, msg, frame) = self.into_parts(filename, source); + MontyException::with_traceback(exc_type, Some(msg), vec![frame]) + } + + /// The exception type, message and the frame locating the error in `filename`. + fn into_parts(self, filename: &str, source: &str) -> (ExcType, String, StackFrame) { let mut source_map = SourceMap::new(source); match self { - Self::Syntax { msg, position } => MontyException::with_traceback( + Self::Syntax { msg, position } => ( ExcType::SyntaxError, - Some(msg.into_owned()), - vec![StackFrame::from_position_syntax_error( - position, - filename, - &mut source_map, - )], + msg.into_owned(), + StackFrame::from_position_syntax_error(position, filename, &mut source_map), ), - Self::NotImplemented { msg, position } => MontyException::with_traceback( + Self::NotImplemented { msg, position } => ( ExcType::NotImplementedError, - Some(format!("The monty syntax parser does not yet support {msg}")), - vec![StackFrame::from_position(position, filename, &mut source_map)], + format!("The monty syntax parser does not yet support {msg}"), + StackFrame::from_position(position, filename, &mut source_map), ), - Self::NotSupported { msg, position } => MontyException::with_traceback( + Self::NotSupported { msg, position } => ( ExcType::NotImplementedError, - Some(msg.into_owned()), - vec![StackFrame::from_position(position, filename, &mut source_map)], + msg.into_owned(), + StackFrame::from_position(position, filename, &mut source_map), ), - Self::Import { msg, position } => MontyException::with_traceback( + Self::Import { msg, position } => ( ExcType::ImportError, - Some(msg.into_owned()), - vec![StackFrame::from_position_no_caret(position, filename, &mut source_map)], + msg.into_owned(), + StackFrame::from_position_no_caret(position, filename, &mut source_map), ), } } diff --git a/crates/bashkit-monty/src/prepare.rs b/crates/bashkit-monty/src/prepare.rs index a8c6fcc3b..c50f95e3a 100644 --- a/crates/bashkit-monty/src/prepare.rs +++ b/crates/bashkit-monty/src/prepare.rs @@ -71,7 +71,7 @@ pub(crate) fn prepare_with_existing_names( } /// How the top-level names of an `eval()` / `exec()` snippet bind. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub(crate) enum SnippetNames { /// An ordinary module compile against the session `NameMap` (`LoadGlobal`): /// the implicit form at module scope. @@ -205,6 +205,12 @@ struct Prepare<'i, 'g> { /// (see [`Self::get_id_read`]). If class bodies ever allow conditional /// bindings this must become a runtime-fallback opcode instead. bound_class_members: AHashSet, + /// Whether the annotation expressions of a synthesized `__annotate__` scope + /// are being prepared: every name, even the scope's `format` parameter, + /// resolves by name at run time (`NameScope::Name`), through the class + /// namespace the function runs under and then the globals, and nothing is + /// captured. Set after the scope's prologue (see `prepare_annotate_body`). + is_annotate: bool, } /// Insertion-ordered bindings for one active comprehension's lexical scope. @@ -521,6 +527,7 @@ impl<'i, 'g> Prepare<'i, 'g> { module_global_names: AHashSet::new(), is_class_scope: false, bound_class_members: AHashSet::new(), + is_annotate: false, } } @@ -635,6 +642,7 @@ impl<'i, 'g> Prepare<'i, 'g> { module_global_names: AHashSet::new(), is_class_scope: false, bound_class_members: AHashSet::new(), + is_annotate: false, }) } @@ -659,8 +667,8 @@ impl<'i, 'g> Prepare<'i, 'g> { Some(expr) => Some(self.prepare_expression(expr)?), None => None, })), - Node::Raise(exc) => { - let expr = match exc { + Node::Raise { exc, cause } => { + let exc = match exc { Some(expr) => { let prepared = self.prepare_expression(expr)?; match prepared.expr { @@ -679,7 +687,12 @@ impl<'i, 'g> Prepare<'i, 'g> { } None => None, }; - new_nodes.push(Node::Raise(expr)); + // A bare class as the cause is instantiated at raise time, so it stays as is. + let cause = match cause { + Some(expr) => Some(self.prepare_expression(expr)?), + None => None, + }; + new_nodes.push(Node::Raise { exc, cause }); } Node::Assert { test, msg } => { let test = self.prepare_expression(test)?; @@ -846,6 +859,8 @@ impl<'i, 'g> Prepare<'i, 'g> { signature, body, is_async, + annotate, + is_annotate, }, decorators, } => { @@ -856,7 +871,7 @@ impl<'i, 'g> Prepare<'i, 'g> { .into_iter() .map(|d| self.prepare_expression(d)) .collect::, ParseError>>()?; - let func = self.prepare_function_def(name, &signature, body, is_async)?; + let func = self.prepare_function_def(name, &signature, body, is_async, annotate, is_annotate)?; // In a class body, the method name becomes a bound member // only now — its own parameter defaults (evaluated in class // scope, above) must see the pre-binding state. @@ -1707,11 +1722,50 @@ impl<'i, 'g> Prepare<'i, 'g> { parsed_sig: &ParsedSignature, body: Vec, is_async: bool, + annotate: Option>, + is_annotate: bool, ) -> Result { // A `def` (top-level, nested, or method — class bodies are function scopes // too) binds its name in the enclosing scope. self.names_assigned_in_order.insert(name.name_id); let name = self.get_id(name)?; + self.prepare_function_scope(name, parsed_sig, body, is_async, annotate, is_annotate) + } + + /// Prepares a `def`'s `__annotate__` (see `Parser::synthesize_annotate`) in + /// this scope, like its defaults. It binds no name: the function is reached + /// through the `Function` that owns it, never through a namespace. + fn prepare_annotate(&mut self, def: RawFunctionDef) -> Result, ParseError> { + let RawFunctionDef { + name, signature, body, .. + } = def; + let name = Identifier::new_with_scope( + name.name_id, + name.position, + NamespaceId::new(0).expect("slot 0 fits in u16"), + NameScope::Local, + ); + self.prepare_function_scope(name, &signature, body, false, None, true) + .map(Box::new) + } + + /// Prepares a function scope whose `name` is already resolved: the body of a + /// `def`, a method or an `__annotate__`. + /// + /// `is_annotate` makes the child an annotate scope (see [`Prepare::is_annotate`]): + /// it captures nothing, so an enclosing local named in an annotation resolves + /// by name at run time (a documented divergence, see `limitations/typing.md`). + fn prepare_function_scope( + &mut self, + name: Identifier, + parsed_sig: &ParsedSignature, + body: Vec, + is_async: bool, + annotate: Option>, + is_annotate: bool, + ) -> Result { + // The annotate function evaluates in this scope, like the defaults. + let annotate = annotate.map(|def| self.prepare_annotate(*def)).transpose()?; // Extract param names from the parsed signature for scope analysis let param_names: Vec = parsed_sig.param_names().collect(); @@ -1721,8 +1775,13 @@ impl<'i, 'g> Prepare<'i, 'g> { // Build `enclosing_locals` for the new function: the union of every // ancestor function scope's locals (see `child_enclosing_locals` for the - // transitive-closure and class-scope-skipping rationale). - let enclosing_locals = self.child_enclosing_locals(); + // transitive-closure and class-scope-skipping rationale). An annotate + // scope sees none, so nothing becomes a cell. + let enclosing_locals = if is_annotate { + AHashSet::new() + } else { + self.child_enclosing_locals() + }; // Filter potential_captures to get actual implicit captures. // Only names that are ALSO in enclosing_locals are true implicit captures. @@ -1752,7 +1811,11 @@ impl<'i, 'g> Prepare<'i, 'g> { )?; // Prepare the function body - let prepared_body = inner_prepare.prepare_nodes(body)?; + let prepared_body = if is_annotate { + inner_prepare.prepare_annotate_body(body)? + } else { + inner_prepare.prepare_nodes(body)? + }; // Take the per-function state out of `inner_prepare` and drop the // child so its `GlobalsRef` borrow is released. We need exclusive @@ -1846,9 +1909,23 @@ impl<'i, 'g> Prepare<'i, 'g> { cell_param_indices, default_exprs, is_async, + annotate, + is_annotate, }) } + /// Prepares a synthesized `__annotate__` body (see `Parser::synthesize_annotate`): + /// the prologue testing `format` as ordinary code, then the returned dict of + /// annotation expressions with every name resolved at run time, so a global + /// named `format` is not shadowed by the parameter, as in CPython. + fn prepare_annotate_body(&mut self, mut body: Vec) -> Result, ParseError> { + let values = body.pop().expect("an annotate body ends with its return"); + let mut prepared = self.prepare_nodes(body)?; + self.is_annotate = true; + prepared.extend(self.prepare_nodes(vec![values])?); + Ok(prepared) + } + /// Prepares a `class Foo: ...` definition. /// /// The class body is a synthetic zero-argument function (see @@ -2000,6 +2077,8 @@ impl<'i, 'g> Prepare<'i, 'g> { cell_param_indices, default_exprs: Vec::new(), is_async: false, + annotate: None, + is_annotate: false, }; Ok(Node::ClassDef { @@ -2164,6 +2243,8 @@ impl<'i, 'g> Prepare<'i, 'g> { cell_param_indices, default_exprs, is_async: false, + annotate: None, + is_annotate: false, }; Ok(ExprLoc::new( @@ -2289,6 +2370,15 @@ impl<'i, 'g> Prepare<'i, 'g> { PrepareState::Function(state) => state, }; + // An annotation expression loads every name at run time, as CPython's + // annotate scope does: the class namespace it runs under, then the + // globals. Its `format` parameter is not visible to it either; only the + // synthesized prologue, prepared before this flag is set, reads that. + if self.is_annotate { + let slot = self.globals.ensure_slot(name_id, position)?; + return Ok(Identifier::new_with_scope(name_id, position, slot, NameScope::Name)); + } + // In a function: walk the scope cascade. // 1. Declared `global` — resolve to a module slot. @@ -2623,7 +2713,7 @@ fn collect_scope_info_from_node( } } Node::FunctionDef { - def: RawFunctionDef { name, .. }, + def: RawFunctionDef { name, signature, .. }, decorators, } => { // Function definition creates a local binding for the function name @@ -2633,6 +2723,10 @@ fn collect_scope_info_from_node( for decorator in decorators { collect_assigned_names_from_expr(decorator, assigned_names, interner); } + // Defaults also evaluate in this scope, unlike the function body. + for default in signature.default_exprs() { + collect_assigned_names_from_expr(default, assigned_names, interner); + } } Node::ClassDef { name, decorators, .. } => { // A class definition binds the class name in this scope, just like a `def`. @@ -2710,9 +2804,14 @@ fn collect_scope_info_from_node( } } // Statements with expressions that may contain walrus operators - Node::Expr(expr) | Node::Return(Some(expr)) | Node::Raise(Some(expr)) => { + Node::Expr(expr) | Node::Return(Some(expr)) => { collect_assigned_names_from_expr(expr, assigned_names, interner); } + Node::Raise { exc, cause } => { + for expr in exc.iter().chain(cause) { + collect_assigned_names_from_expr(expr, assigned_names, interner); + } + } Node::Assert { test, msg } => { collect_assigned_names_from_expr(test, assigned_names, interner); if let Some(m) = msg { @@ -2720,7 +2819,7 @@ fn collect_scope_info_from_node( } } // These don't create new names - Node::Pass | Node::Return(None) | Node::Raise(None) | Node::Break { .. } | Node::Continue { .. } => {} + Node::Pass | Node::Return(None) | Node::Break { .. } | Node::Continue { .. } => {} } } @@ -2928,6 +3027,11 @@ fn collect_cell_vars_from_node( interner: &CompileInterns<'_>, ) { match node { + // A class body's `__annotate__` captures nothing (see `Prepare::is_annotate`). + Node::FunctionDef { + def: RawFunctionDef { is_annotate: true, .. }, + .. + } => {} Node::FunctionDef { def: RawFunctionDef { signature, body, .. }, decorators, @@ -3036,9 +3140,14 @@ fn collect_cell_vars_from_node( } } // Handle expressions that may contain lambdas - Node::Expr(expr) | Node::Return(Some(expr)) | Node::Raise(Some(expr)) => { + Node::Expr(expr) | Node::Return(Some(expr)) => { collect_cell_vars_from_expr(expr, our_locals, cell_vars, interner); } + Node::Raise { exc, cause } => { + for expr in exc.iter().chain(cause) { + collect_cell_vars_from_expr(expr, our_locals, cell_vars, interner); + } + } Node::Assert { test, msg } => { collect_cell_vars_from_expr(test, our_locals, cell_vars, interner); if let Some(msg) = msg { @@ -3089,7 +3198,6 @@ fn collect_cell_vars_from_node( // stores as plain stores and its later loads as cell loads. Node::Pass | Node::Return(None) - | Node::Raise(None) | Node::Break { .. } | Node::Continue { .. } | Node::Global { .. } @@ -3443,10 +3551,15 @@ fn collect_referenced_names_from_node( interner: &CompileInterns<'_>, ) { match node { - Node::Expr(expr) | Node::Return(Some(expr)) | Node::Raise(Some(expr)) => { + Node::Expr(expr) | Node::Return(Some(expr)) => { collect_referenced_names_from_expr(expr, referenced, interner); } - Node::Return(None) | Node::Raise(None) => {} + Node::Raise { exc, cause } => { + for expr in exc.iter().chain(cause) { + collect_referenced_names_from_expr(expr, referenced, interner); + } + } + Node::Return(None) => {} Node::Assert { test, msg } => { collect_referenced_names_from_expr(test, referenced, interner); if let Some(m) = msg { @@ -3528,6 +3641,11 @@ fn collect_referenced_names_from_node( collect_referenced_names_from_node(n, referenced, interner); } } + // A class body's `__annotate__` references nothing from enclosing scopes. + Node::FunctionDef { + def: RawFunctionDef { is_annotate: true, .. }, + .. + } => {} Node::FunctionDef { def: RawFunctionDef { signature, body, .. }, decorators, diff --git a/crates/bashkit-monty/src/py_value.rs b/crates/bashkit-monty/src/py_value.rs index c9b7aad72..8ec585866 100644 --- a/crates/bashkit-monty/src/py_value.rs +++ b/crates/bashkit-monty/src/py_value.rs @@ -11,6 +11,7 @@ use std::{ use num_bigint::BigInt; use crate::{ + annotations, args::ArgValues, builtins::{Builtins, BuiltinsFunctions}, bytecode::{CallResult, VM}, @@ -23,7 +24,7 @@ use crate::{ intern::{FunctionId, StaticStrings}, modules::{ModuleFunctions, collections::defaultdict::defaultdict_missing}, types::{ - GenericAlias, LazyHeapSet, LongInt, Property, PyTrait, Type, Union, allocate_string, + BuiltinType, GenericAlias, LazyHeapSet, LongInt, Property, PyTrait, Type, Union, allocate_string, bytes::PyBytes, long_int::{PyInt, arithmetic::float_binary}, numeric::{round_digits, round_float}, @@ -155,6 +156,26 @@ macro_rules! numeric_binary { } impl<'h> PyValue<'h> { + /// Converts an integer or an object implementing `__index__` into a repetition count. + /// Returns `None` for unsupported operands; out-of-range counts raise `OverflowError`. + /// Negative counts within range become zero. + pub(crate) fn repeat_count(self, vm: &mut VM<'h>) -> RunResult> { + let count = self.py_index_impl(vm)?; + // An integer may return itself; release its reader before cleaning up the result. + drop(self); + let Some(count) = count else { + return Ok(None); + }; + defer_drop!(count, vm); + + // Check overflow before clamping: even an oversized negative count must raise. + let count = count.as_int_with_overflow(vm, || ExcType::overflow_index_sized_int().into())?; + // In-range negatives mean no repetitions; check that the result fits the host's usize. + Ok(Some( + usize::try_from(count.max(0)).map_err(|_| ExcType::overflow_index_sized_int())?, + )) + } + /// Includes the mutating `defaultdict.__missing__` path outside `PyTrait`. pub(crate) fn subscript(self, key: &Value, vm: &mut VM<'h>) -> RunResult { match self { @@ -193,7 +214,7 @@ impl<'h> PyValue<'h> { Self::Property(value) => Ok(write!(f, "")?), Self::Cell(cell) => Ok(write!(f, "", cell.get(vm.heap).0.py_type_name(vm))?), Self::Exception(e) => Ok(e.get(vm.heap).py_repr_fmt(f)?), - Self::Module(m) => Ok(write!(f, "", m.get(vm.heap).name_str(vm.interns))?), + Self::Module(m) => Ok(f.write_str(&m.get(vm.heap).repr(vm.interns))?), Self::Coroutine(coro) => { let func = vm.interns.get_function(coro.get(vm.heap).func_id); Ok(write!(f, "", vm.interns.get_str(func.name.name_id))?) @@ -531,7 +552,13 @@ impl<'h> PyTrait<'h> for PyValue<'h> { fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult { forward_py_value!(self, |value| value.py_call_attr(vm, attr, args), { Self::Module(value) => value.py_call_attr(vm, attr, args), - Self::Builtin(Builtins::Type(ty)) if let EitherStr::Interned(id) = attr => ty.call_class_method(*id, args, vm), + Self::Builtin(Builtins::Type(ty)) => Type::from(*ty).call_class_method(attr, args, vm), + Self::DefFunction(func_id) => { + match annotations::function_call_attr(*func_id, None, attr.as_str(vm.interns), args, vm) { + Some(result) => result, + None => Err(ExcType::attribute_error(self.py_type_name(vm), attr.as_str(vm.interns))), + } + } _ => { args.drop_with(vm); Err(ExcType::attribute_error(self.py_type_name(vm), attr.as_str(vm.interns))) @@ -541,11 +568,23 @@ impl<'h> PyTrait<'h> for PyValue<'h> { fn py_getitem(&self, key: &Value, vm: &mut VM<'h>) -> RunResult { forward_py_value!(self, |value| value.py_getitem(key, vm), { - Self::Builtin(Builtins::Type(t)) if t.has_class_getitem() => Ok(GenericAlias::subscript(*t, key.clone_with_heap(vm), vm)), - Self::Builtin(Builtins::Function(BuiltinsFunctions::Type)) => Ok(GenericAlias::subscript(Type::Type, key.clone_with_heap(vm), vm)), - Self::Builtin(Builtins::Type(Type::Union)) => Union::subscript(key.clone_with_heap(vm), vm), + Self::Builtin(Builtins::Type(t)) if Type::from(*t).has_class_getitem() => Ok(GenericAlias::subscript(*t, key.clone_with_heap(vm), vm)), + Self::Builtin(Builtins::Function(BuiltinsFunctions::Type)) => Ok(GenericAlias::subscript(BuiltinType::Type, key.clone_with_heap(vm), vm)), + Self::Builtin(Builtins::Type(BuiltinType::Union)) => Union::subscript(key.clone_with_heap(vm), vm), Self::Marker(Marker(StaticStrings::Optional)) => Union::optional(key.clone_with_heap(vm), vm), - Self::Builtin(Builtins::Type(t)) => Err(ExcType::type_error_type_not_subscriptable(&t.name(vm.heap, vm.interns))), + Self::Marker(form) if form.is_generic_form() => GenericAlias::subscript_special(*form, key.clone_with_heap(vm), vm), + // CPython's wording per kind of `typing` object: `Any` and `TypeVar` + // are classes, `Self` and friends special forms, the two bases generic. + Self::Marker(Marker(StaticStrings::Any)) => Err(ExcType::type_error_type_not_subscriptable("Any")), + Self::Marker(Marker(StaticStrings::TypeVar)) => Err(ExcType::type_error_type_not_subscriptable("typing.TypeVar")), + Self::Marker(Marker(form @ (StaticStrings::Generic | StaticStrings::Protocol))) => Err(ExcType::type_error(format!( + "Parameters to {}[...] must all be type variables or parameter specification variables.", + <&str>::from(*form) + ))), + Self::Marker(form) if form.py_type() == Type::SpecialForm => { + Err(ExcType::type_error(format!("typing.{} is not subscriptable", <&str>::from(form.0)))) + } + Self::Builtin(Builtins::Type(t)) => Err(ExcType::type_error_type_not_subscriptable(&Type::from(*t).name(vm.heap, vm.interns))), Self::Builtin(Builtins::ExcType(exc_type)) => Err(ExcType::type_error_type_not_subscriptable((*exc_type).into())), _ => Err(ExcType::type_error_not_sub(&self.py_type_name(vm))), }) diff --git a/crates/bashkit-monty/src/repl.rs b/crates/bashkit-monty/src/repl.rs index 4a615c5e8..13f35868b 100644 --- a/crates/bashkit-monty/src/repl.rs +++ b/crates/bashkit-monty/src/repl.rs @@ -22,7 +22,7 @@ use ruff_python_parser::{InterpolatedStringErrorType, LexicalErrorType, ParseErr use crate::{ args::{ArgValues, KwargsValues}, - bytecode::{FrameExit, VM, VMSnapshot}, + bytecode::{FrameExit, ModuleCache, VM, VMSnapshot}, defer_drop, exception_private::{ExcTypeExt, RunError}, heap::{DropWithContext, Heap, HeapData, HeapReader}, @@ -89,6 +89,14 @@ pub struct MontyRepl { /// The session's `random` state, carried between snippets like the /// globals so a `random.seed()` in one feed governs the draws of the next. random: SessionRandom, + /// Modules imported from files, carried between snippets like the globals + /// so each file runs once per session. + #[serde(default)] + modules: ModuleCache, + /// Whether a feed has run `from __future__ import annotations`, which then + /// applies to every later feed, as in CPython's interactive mode. + #[serde(default)] + future_annotations: bool, /// Persistent heap across snippets. heap: Heap, /// Persistent global variable values across snippets. @@ -101,8 +109,8 @@ pub struct MontyRepl { impl MontyRepl { /// The session heap and interns, for a dump upgrade of an idle session. - pub(crate) fn heap_and_interns(&mut self) -> (&mut Heap, &Interns) { - (&mut self.heap, &self.interns) + pub(crate) fn heap_and_interns(&mut self) -> (&mut Heap, &mut Interns) { + (&mut self.heap, &mut self.interns) } /// Creates an empty REPL session with no code parsed or executed. @@ -124,6 +132,8 @@ impl MontyRepl { os_policy: Arc::new(OsPolicy::default()), cwd: Arc::from(DEFAULT_CWD), random: SessionRandom::default(), + modules: ModuleCache::default(), + future_annotations: false, heap, globals: Vec::new(), } @@ -155,10 +165,16 @@ impl MontyRepl { /// [`MontyRun::with_os_policy`](crate::MontyRun::with_os_policy). #[must_use] pub fn with_os_policy(mut self, os_policy: OsPolicy) -> Self { - self.os_policy = Arc::new(os_policy); + self.set_os_policy(os_policy); self } + /// Replaces the session's OS-call policies in place, for a host restoring + /// a dump under its own policy (see [`ReplProgress::set_os_policy`]). + pub fn set_os_policy(&mut self, os_policy: OsPolicy) { + self.os_policy = Arc::new(os_policy); + } + /// Switches the sandbox working directory (initially `/`). /// /// `cwd` is an absolute POSIX virtual path, normalized here like @@ -258,6 +274,7 @@ impl MontyRepl { script_name: &this.script_name, cwd: &this.cwd, os_policy: &this.os_policy, + future_annotations: this.future_annotations, }; let mut executor = match Executor::new_repl_snippet( code, @@ -271,6 +288,7 @@ impl MontyRepl { Ok(exec) => exec, Err(error) => return Err(Box::new(ReplStartError { repl: this, error })), }; + this.future_annotations = executor.program.module_code.future_annotations(); this.ensure_globals_size(executor.namespace_size()); @@ -288,10 +306,17 @@ impl MontyRepl { ); vm.random = mem::take(&mut this.random); + vm.modules = mem::take(&mut this.modules); // Inject inputs with VM alive if let Err(error) = inject_inputs_into_vm(&executor.program, input_values, &input_ids, &mut vm) { - reclaim_vm_state(&mut this.globals, &mut this.cwd, &mut this.random, &mut vm); + reclaim_vm_state( + &mut this.globals, + &mut this.cwd, + &mut this.random, + &mut this.modules, + &mut vm, + ); return Err(error); } @@ -302,7 +327,13 @@ impl MontyRepl { let vm_state = if converted.needs_snapshot() { Some(vm.snapshot()) } else { - reclaim_vm_state(&mut this.globals, &mut this.cwd, &mut this.random, &mut vm); + reclaim_vm_state( + &mut this.globals, + &mut this.cwd, + &mut this.random, + &mut this.modules, + &mut vm, + ); None }; Ok((converted, vm_state)) @@ -353,6 +384,7 @@ impl MontyRepl { script_name: &self.script_name, cwd: &self.cwd, os_policy: &self.os_policy, + future_annotations: self.future_annotations, }; let mut executor = Executor::new_repl_snippet( code, @@ -363,6 +395,7 @@ impl MontyRepl { self.options, session, )?; + self.future_annotations = executor.program.module_code.future_annotations(); self.ensure_globals_size(executor.namespace_size()); @@ -380,16 +413,29 @@ impl MontyRepl { ); vm.random = mem::take(&mut self.random); + vm.modules = mem::take(&mut self.modules); if let Err(e) = inject_inputs_into_vm(&executor.program, input_values, &input_ids, &mut vm) { - reclaim_vm_state(&mut self.globals, &mut self.cwd, &mut self.random, &mut vm); + reclaim_vm_state( + &mut self.globals, + &mut self.cwd, + &mut self.random, + &mut self.modules, + &mut vm, + ); return Err(e); } let result = Program::run_to_completion(&mut vm); // Reclaim globals (and any directory change or seed) before cleanup. - reclaim_vm_state(&mut self.globals, &mut self.cwd, &mut self.random, &mut vm); + reclaim_vm_state( + &mut self.globals, + &mut self.cwd, + &mut self.random, + &mut self.modules, + &mut vm, + ); Ok(result) }, ); @@ -456,6 +502,7 @@ impl MontyRepl { script_name: &self.script_name, cwd: &self.cwd, os_policy: &self.os_policy, + future_annotations: self.future_annotations, }, )?; self.sources.insert(input_script_name, executor.program.code.clone()); @@ -476,6 +523,7 @@ impl MontyRepl { ); vm.random = mem::take(&mut self.random); + vm.modules = mem::take(&mut self.modules); let result = match convert_args(args, vm) { Ok(args) => { let (args, kwargs) = args.into_parts(); @@ -489,7 +537,15 @@ impl MontyRepl { let mut run_result = vm.run_external(); loop { run_result = match run_result { - Ok(FrameExit::Return(value)) => break Ok(MontyObject::export(value, vm)), + Ok(FrameExit::Return(value)) => { + break vm + .export_on_clock(|vm| MontyObject::export(value, vm)) + .map_err(|error| { + error.into_python_exception(vm.interns, |fname| { + self.sources.get(fname).map(|source| &**source) + }) + }); + } // No host answers inside a host-driven call, so the // lookup is `Undefined`: `hasattr()` is False, // `getattr()` yields its default. @@ -521,6 +577,7 @@ impl MontyRepl { let args_slot = executor.program.input_slots[0].index(); mem::replace(&mut globals[args_slot], Value::Undefined).drop_with(vm); self.random = mem::take(&mut vm.random); + self.modules = mem::take(&mut vm.modules); self.globals = globals; if let Some(cwd) = vm.take_changed_cwd() { self.cwd = Arc::from(cwd); @@ -675,15 +732,15 @@ pub struct ReplStartError { impl ReplProgress { /// The session heap and the interns its values refer to, for a dump upgrade. /// While a snippet is in flight the executor holds the session's interns. - pub(crate) fn heap_and_interns(&mut self) -> (&mut Heap, &Interns) { + pub(crate) fn heap_and_interns(&mut self) -> (&mut Heap, &mut Interns) { match self { Self::FunctionCall(ReplFunctionCall { snapshot, .. }) | Self::OsCall(ReplOsCall { snapshot, .. }) | Self::NameLookup(ReplNameLookup { snapshot, .. }) => { - (&mut snapshot.repl.heap, &snapshot.executor.tables.interns) + (&mut snapshot.repl.heap, &mut snapshot.executor.tables.interns) } Self::ResolveFutures(ReplResolveFutures { repl, executor, .. }) => { - (&mut repl.heap, &executor.tables.interns) + (&mut repl.heap, &mut executor.tables.interns) } Self::Complete { repl, .. } => repl.heap_and_interns(), } @@ -768,6 +825,22 @@ impl ReplProgress { Self::Complete { repl, .. } => repl.tracker_mut(), } } + + /// Replaces the OS-call policies of the session and of a suspended snippet. + /// + /// A dump carries the policy it was taken under; hosts restoring it call this + /// so the restoring side's clock, zone, sleep and entropy policy governs every + /// later call. A call already suspended keeps the shape it was issued with. + pub fn set_os_policy(&mut self, os_policy: OsPolicy) { + let os_policy = Arc::new(os_policy); + match self { + Self::FunctionCall(call) => call.snapshot.set_os_policy(os_policy), + Self::OsCall(call) => call.snapshot.set_os_policy(os_policy), + Self::ResolveFutures(state) => state.set_os_policy(os_policy), + Self::NameLookup(lookup) => lookup.snapshot.set_os_policy(os_policy), + Self::Complete { repl, .. } => repl.os_policy = os_policy, + } + } } // --------------------------------------------------------------------------- @@ -1005,7 +1078,13 @@ impl ReplNameLookup { let vm_state = if converted.needs_snapshot() { Some(vm.snapshot()) } else { - reclaim_vm_state(&mut repl.globals, &mut repl.cwd, &mut repl.random, &mut vm); + reclaim_vm_state( + &mut repl.globals, + &mut repl.cwd, + &mut repl.random, + &mut repl.modules, + &mut vm, + ); None }; (converted, vm_state) @@ -1037,6 +1116,12 @@ pub struct ReplResolveFutures { } impl ReplResolveFutures { + /// Points the session and the blocked snippet's program at `os_policy`, + /// as [`ReplSnapshot`] does for the other suspensions. + fn set_os_policy(&mut self, os_policy: Arc) { + set_session_os_policy(&mut self.repl, &mut self.executor, os_policy); + } + /// Extracts the REPL session, restoring globals from the suspended VM state. /// /// As with the other REPL snapshot types, globals live inside the VM @@ -1054,10 +1139,11 @@ impl ReplResolveFutures { vm_state, .. } = self; - let (globals, cwd, random) = vm_state.abandon(&mut repl.heap); - repl.globals = globals; - repl.cwd = Arc::from(cwd); - repl.random = random; + let state = vm_state.abandon(&mut repl.heap); + repl.globals = state.globals; + repl.cwd = Arc::from(state.cwd); + repl.random = state.random; + repl.modules = state.modules; repl.commit_executor(executor); repl } @@ -1125,7 +1211,13 @@ impl ReplResolveFutures { ); if let Some(call_id) = invalid_call_id { - reclaim_vm_state(&mut repl.globals, &mut repl.cwd, &mut repl.random, &mut vm); + reclaim_vm_state( + &mut repl.globals, + &mut repl.cwd, + &mut repl.random, + &mut repl.modules, + &mut vm, + ); return Err(MontyException::runtime_error(format!( "unknown call_id {call_id}, expected one of: {pending_call_ids:?}" ))); @@ -1138,7 +1230,13 @@ impl ReplResolveFutures { let vm_state = if converted.needs_snapshot() { Some(vm.snapshot()) } else { - reclaim_vm_state(&mut repl.globals, &mut repl.cwd, &mut repl.random, &mut vm); + reclaim_vm_state( + &mut repl.globals, + &mut repl.cwd, + &mut repl.random, + &mut repl.modules, + &mut vm, + ); None }; Ok((converted, vm_state)) @@ -1269,7 +1367,13 @@ fn abort_restored( let vm_result = vm.abort(exc); let converted = convert_frame_exit(vm_result, &mut vm); // Uncatchable exceptions cannot suspend, so no snapshot is needed. - reclaim_vm_state(&mut repl.globals, &mut repl.cwd, &mut repl.random, &mut vm); + reclaim_vm_state( + &mut repl.globals, + &mut repl.cwd, + &mut repl.random, + &mut repl.modules, + &mut vm, + ); converted }, ); @@ -1290,6 +1394,12 @@ pub(crate) struct ReplSnapshot { } impl ReplSnapshot { + /// Points both the session and the suspended snippet's program at `os_policy`, + /// which a resumed VM reads from the program. + fn set_os_policy(&mut self, os_policy: Arc) { + set_session_os_policy(&mut self.repl, &mut self.executor, os_policy); + } + /// Raises `exc` uncatchably at the suspension point. fn abort(self, exc: MontyException, print: PrintWriter<'_>) -> Result> { let Self { @@ -1313,10 +1423,11 @@ impl ReplSnapshot { executor, vm_state, } = self; - let (globals, cwd, random) = vm_state.abandon(&mut repl.heap); - repl.globals = globals; - repl.cwd = Arc::from(cwd); - repl.random = random; + let state = vm_state.abandon(&mut repl.heap); + repl.globals = state.globals; + repl.cwd = Arc::from(state.cwd); + repl.random = state.random; + repl.modules = state.modules; repl.commit_executor(executor); repl } @@ -1364,7 +1475,13 @@ impl ReplSnapshot { let vm_state = if converted.needs_snapshot() { Some(vm.snapshot()) } else { - reclaim_vm_state(&mut repl.globals, &mut repl.cwd, &mut repl.random, &mut vm); + reclaim_vm_state( + &mut repl.globals, + &mut repl.cwd, + &mut repl.random, + &mut repl.modules, + &mut vm, + ); None }; (converted, vm_state) @@ -1379,15 +1496,22 @@ impl ReplSnapshot { // --------------------------------------------------------------------------- /// Reclaims what outlives a snippet from its finished VM: the globals, the -/// `random` generator, and the working directory when the snippet (or the -/// snapshot it resumed from) owns one, so an `os.chdir` or a `random.seed()` -/// persists into later feeds like the globals do. -fn reclaim_vm_state(globals: &mut Vec, cwd: &mut Arc, random: &mut SessionRandom, vm: &mut VM<'_>) { +/// `random` generator, the file modules, and the working directory when the +/// snippet (or the snapshot it resumed from) owns one, so an `os.chdir`, a +/// `random.seed()` or an import persists into later feeds like the globals do. +fn reclaim_vm_state( + globals: &mut Vec, + cwd: &mut Arc, + random: &mut SessionRandom, + modules: &mut ModuleCache, + vm: &mut VM<'_>, +) { *globals = vm.take_globals(); if let Some(changed) = vm.take_changed_cwd() { *cwd = Arc::from(changed); } *random = mem::take(&mut vm.random); + *modules = mem::take(&mut vm.modules); } /// Injects input values into the VM's global namespace slots. @@ -1548,3 +1672,10 @@ fn is_callable(value: &Value, heap: &Heap) -> bool { _ => false, } } + +/// Gives a suspended session and its snippet's program the same `os_policy`; +/// the resumed VM reads the program's copy, later snippets the session's. +fn set_session_os_policy(repl: &mut MontyRepl, executor: &mut Executor, os_policy: Arc) { + executor.program.os_policy = Arc::clone(&os_policy); + repl.os_policy = os_policy; +} diff --git a/crates/bashkit-monty/src/resource_checks.rs b/crates/bashkit-monty/src/resource_checks.rs index 472ef9278..000d3625b 100644 --- a/crates/bashkit-monty/src/resource_checks.rs +++ b/crates/bashkit-monty/src/resource_checks.rs @@ -3,7 +3,7 @@ use monty_types::{ExcType, LARGE_RESULT_THRESHOLD, ResourceError, ResourceTracke use crate::{ bytecode::VM, - exception_private::{RunError, RunResult, SimpleException}, + exception_private::{ExcTypeExt, RunError, RunResult, SimpleException}, value::{VALUE_SIZE, Value}, }; @@ -16,6 +16,30 @@ pub fn check_repeat_size(item_len: usize, count: usize, tracker: &ResourceTracke check_estimated_size(item_len.saturating_mul(count), tracker) } +/// The length of `len * count` repetitions, or CPython's message-less +/// `MemoryError` when a buffer of `elem_size`-byte elements that long could not +/// be addressed at all (`[1, 2] * 2**62`), instead of a capacity-overflow panic. +pub(crate) fn repeated_len(len: usize, count: usize, elem_size: usize) -> RunResult { + len.checked_mul(count) + .filter(|total| { + total + .checked_mul(elem_size) + .is_some_and(|bytes| bytes <= isize::MAX.unsigned_abs()) + }) + .ok_or_else(ExcType::allocation_too_large) +} + +/// Allocates an empty `Vec` with room for `capacity` elements, raising `MemoryError` +/// rather than aborting when the allocator refuses; with no `max_memory` set +/// nothing else stops an attacker-sized repetition. +pub(crate) fn try_vec_with_capacity(capacity: usize) -> RunResult> { + let mut buffer = Vec::new(); + buffer + .try_reserve_exact(capacity) + .map_err(|_| ExcType::allocation_too_large())?; + Ok(buffer) +} + /// Pre-checks that `base ** exponent` won't exceed resource limits before computing. /// /// The result of `base ** exp` has approximately `base_bits * exp` bits. @@ -105,6 +129,65 @@ pub fn check_replace_size( check_estimated_size(estimated, tracker) } +/// Collects an iterator into a `Vec`, preflighting each reallocation of the buffer. +/// +/// For scans bounded only by an attacker-sized input (split pieces), whose +/// buffer would otherwise double past the allocator's hard headroom before any +/// checkpoint. Also polls the time limit; see [`push_checked`]. +pub(crate) fn collect_checked( + items: impl IntoIterator, + tracker: &ResourceTracker, +) -> Result, ResourceError> { + let mut items = items.into_iter(); + let Some(first) = items.next() else { + return Ok(Vec::new()); + }; + // Allocate directly as std's `collect` does: a first push into an empty `Vec` + // takes the generic, out-of-line grow path, which dominates a short split. + let mut collected = Vec::with_capacity(4); + collected.push(first); + for item in items { + push_checked(&mut collected, item, tracker)?; + } + Ok(collected) +} + +/// Pushes one item onto a scan buffer after [`ResourceTracker::check_growth`] and an +/// amortized time poll; the single-push form of [`collect_checked`]. +/// +/// Scan pieces cost a few nanoseconds each, so the hot path is one branch: the growth +/// check and clock read run only at a capacity boundary or every [`SCAN_CHECK_INTERVAL`] pushes. +#[inline] +pub(crate) fn push_checked(buffer: &mut Vec, item: T, tracker: &ResourceTracker) -> Result<(), ResourceError> { + let len = buffer.len(); + if len == buffer.capacity() || len % SCAN_CHECK_INTERVAL == SCAN_CHECK_INTERVAL - 1 { + check_scan_buffer(len, buffer.capacity(), size_of::(), tracker)?; + } + buffer.push(item); + Ok(()) +} + +/// Pushes between time polls in [`push_checked`]: wider than +/// `ResourceTracker::LOOP_CHECK_INTERVAL` because a scan push is far cheaper than a +/// loop iteration that allocates. +const SCAN_CHECK_INTERVAL: usize = 1024; + +/// The cold half of [`push_checked`]: the growth preflight, plus a time poll on every +/// [`SCAN_CHECK_INTERVAL`]th push, so a short scan never reads the clock. +#[cold] +#[inline(never)] +fn check_scan_buffer( + len: usize, + capacity: usize, + elem_size: usize, + tracker: &ResourceTracker, +) -> Result<(), ResourceError> { + if len % SCAN_CHECK_INTERVAL == SCAN_CHECK_INTERVAL - 1 { + tracker.check_time()?; + } + tracker.check_growth(len, capacity, elem_size) +} + /// Pre-checks the reallocation a push into a full `Value` buffer causes, /// dropping `item` if the container cannot grow. /// diff --git a/crates/bashkit-monty/src/run.rs b/crates/bashkit-monty/src/run.rs index 2e4cb7ac9..987924b41 100644 --- a/crates/bashkit-monty/src/run.rs +++ b/crates/bashkit-monty/src/run.rs @@ -353,6 +353,9 @@ pub(crate) struct ReplSession<'a> { pub(crate) cwd: &'a Arc, /// Clock, sleep and random initialization policies. pub(crate) os_policy: &'a Arc, + /// Whether an earlier feed ran `from __future__ import annotations`, which + /// persists for the rest of the session as in CPython's interactive mode. + pub(crate) future_annotations: bool, } impl Executor { @@ -374,6 +377,7 @@ impl Executor { CompileInterns::direct(&mut interns), input_names, options, + false, )?; let namespace_size = globals.len(); @@ -426,6 +430,7 @@ impl Executor { CompileInterns::new(interns), input_names, options, + session.future_annotations, ); if compiled.is_err() { globals.truncate(globals_len); @@ -509,7 +514,8 @@ impl Executor { .emit(Opcode::ReturnValue) .map_err(|e| e.into_python_exc(script_name, &code))?; - let module_code = builder.build(); + // A callable bound to `exec` / `eval` inherits the session's `__future__` state from this frame. + let module_code = builder.build().with_future_annotations(session.future_annotations); overlay.commit(); let tables = SessionTables { global_names: existing_globals, @@ -746,12 +752,14 @@ impl Program { args.drop_with(vm); frame_exit_result = vm.resume_with_exception(err); } - // An import nobody serves is a missing module. + // An import nobody serves is a missing module, and host hints are `{}`. Ok(FrameExit::OsCall { - function_call: call @ OsFunctionCall::Import(_), + function_call: call @ (OsFunctionCall::Import(_) | OsFunctionCall::GetTypeHints(_)), + effect, .. }) => { - frame_exit_result = resume_with_result(vm, ExtFunctionResult::Error(call.on_no_handler()), None); + vm.pending_effect = effect; + frame_exit_result = resume_with_result(vm, call.no_handler_result(), None); } // Standard execution waits inline, excluding sleep from execution time. Ok(FrameExit::OsCall { @@ -797,7 +805,7 @@ pub(crate) fn frame_exit_to_object(frame_exit_result: RunResult, vm: // so one `drop_with` releases whatever the exit owns, fields added later // included. let exit = match answer_unserved_lookups(frame_exit_result, vm)? { - FrameExit::Return(return_value) => return Ok(MontyObject::export(return_value, vm)), + FrameExit::Return(return_value) => return vm.export_on_clock(|vm| MontyObject::export(return_value, vm)), exit => exit, }; let error: RunError = match &exit { @@ -851,7 +859,8 @@ pub struct RefCountOutput { /// Compiles module source through the supplied tables, committing any overlay on success. /// On failure the caller restores provisional global slots or discards a fresh program's tables. /// The source must already have passed the nesting scan; `MontyRun::new` and -/// the REPL feeds run it. +/// the REPL feeds run it. `future_annotations` is inherited from earlier REPL feeds; +/// the returned `Code` records it, or a `from __future__ import annotations` in `code`. fn compile_module_source( code: &str, script_name: &str, @@ -859,6 +868,7 @@ fn compile_module_source( mut interns: CompileInterns<'_>, input_names: impl IntoIterator>, options: CompileOptions, + future_annotations: bool, ) -> Result<(Code, Vec), MontyException> { let input_names = input_names.into_iter(); let mut input_slots = Vec::with_capacity(input_names.size_hint().0); @@ -869,11 +879,11 @@ fn compile_module_source( .map_err(|e| e.into_python_exc(script_name, code))?; input_slots.push(slot); } - let nodes = - parse_with_interner(code, script_name, &mut interns).map_err(|e| e.into_python_exc(script_name, code))?; - let nodes = - prepare_with_existing_names(nodes, &interns, globals).map_err(|e| e.into_python_exc(script_name, code))?; - let module_code = Compiler::compile_module(&nodes, &mut interns, globals, options) + let parsed = parse_with_interner(code, script_name, &mut interns, future_annotations) + .map_err(|e| e.into_python_exc(script_name, code))?; + let nodes = prepare_with_existing_names(parsed.nodes, &interns, globals) + .map_err(|e| e.into_python_exc(script_name, code))?; + let module_code = Compiler::compile_module(&nodes, &mut interns, globals, options, parsed.future_annotations) .map_err(|e| e.into_python_exc(script_name, code))?; interns.commit(); Ok((module_code, input_slots)) diff --git a/crates/bashkit-monty/src/run_progress.rs b/crates/bashkit-monty/src/run_progress.rs index f3901106b..209742839 100644 --- a/crates/bashkit-monty/src/run_progress.rs +++ b/crates/bashkit-monty/src/run_progress.rs @@ -15,10 +15,10 @@ use monty_types::{ use crate::{ asyncio::CallId, - bytecode::{FrameExit, PendingLookupEffect, VM, VMSnapshot}, - exception_private::{ExcTypeExt, ExceptionRaise, RunError, RunResult, SimpleException}, + bytecode::{FrameExit, PendingImport, PendingLookupEffect, VM, VMSnapshot}, + exception_private::{ExcTypeExt, RunError, RunResult, SimpleException}, heap::{DropWithContext, Heap, HeapReader}, - intern::{Interns, StringId}, + intern::Interns, object_bridge::MontyObjectExt, os_dispatch::{PendingEffect, PostConversionEffect, release_pending_effect}, run::Executor, @@ -52,14 +52,14 @@ pub enum RunProgress { impl RunProgress { /// The execution heap and its interns for a dump upgrade, or `None` once /// execution has completed. - pub(crate) fn heap_and_interns(&mut self) -> Option<(&mut Heap, &Interns)> { + pub(crate) fn heap_and_interns(&mut self) -> Option<(&mut Heap, &mut Interns)> { match self { Self::FunctionCall(FunctionCall { snapshot, .. }) | Self::OsCall(OsCall { snapshot, .. }) | Self::NameLookup(NameLookup { snapshot, .. }) => { - Some((&mut snapshot.heap, &snapshot.executor.tables.interns)) + Some((&mut snapshot.heap, &mut snapshot.executor.tables.interns)) } - Self::ResolveFutures(ResolveFutures { heap, executor, .. }) => Some((heap, &executor.tables.interns)), + Self::ResolveFutures(ResolveFutures { heap, executor, .. }) => Some((heap, &mut executor.tables.interns)), Self::Complete(_) => None, } } @@ -587,7 +587,7 @@ fn import_from_error(err: RunError, name: &str, vm: &VM<'_>) -> RunError { return err; } if let Some(module) = vm.suspended_import_from() { - ExcType::cannot_import_name(name, vm.interns.get_str(module)) + ExcType::cannot_import_name(name, vm.interns.get_str(module), None) } else if let Some(path) = vm.suspended_submodule() { ExcType::module_not_found_error(vm.interns.get_str(path), None) } else { @@ -927,8 +927,14 @@ pub(crate) fn resume_with_result( result: ExtFunctionResult, eager_call_id: Option, ) -> Result { + // An `import` call: armed as the pending effect, or, in a dump written + // before file imports, named by the suspended `LoadModule`. + if let Some(pending) = vm.take_pending_import() { + return vm.resume_import(pending, result, eager_call_id); + } if let Some(module_id) = vm.suspended_import() { - return resume_import(vm, module_id, result, eager_call_id); + let pending = PendingImport::top_level(vm.interns.get_str(module_id).to_owned()); + return vm.resume_import(pending, result, eager_call_id); } // An eager answer and a future both register the call's future; the // eager one settles it in the same step. @@ -973,38 +979,11 @@ pub(crate) fn resume_with_result( (ExtFunctionResult::NotFound(function_name), None) => { vm.resume_with_exception(ExtFunctionResult::not_found_exc(&function_name)) } + (ExtFunctionResult::ModuleFile(_), None) => vm.resume_with_exception(ExcType::module_file_for_non_import()), (ExtFunctionResult::Future(_), None) => unreachable!("a future answer always carries its call id"), } } -/// Resumes an import with the host's module value or raises its exception without carets. -/// `NotFound` raises `ModuleNotFoundError`; futures are rejected because imports cannot await. -fn resume_import( - vm: &mut VM<'_>, - module_id: StringId, - result: ExtFunctionResult, - eager_call_id: Option, -) -> Result { - match (result, eager_call_id) { - (ExtFunctionResult::Return(obj), None) => vm.resume(obj), - (ExtFunctionResult::Error(exc), None) => { - let mut raise = ExceptionRaise::from(exc); - raise.hide_caret = true; - vm.resume_with_exception(RunError::Exc(raise)) - } - (ExtFunctionResult::NotFound(_), None) => { - vm.resume_with_exception(ExcType::module_not_found_error(vm.interns.get_str(module_id), None)) - } - (ExtFunctionResult::Future(_), _) | (_, Some(_)) => { - let message = format!( - "import of '{}' cannot be answered with a future", - vm.interns.get_str(module_id) - ); - vm.resume_with_exception(SimpleException::new_msg(ExcType::RuntimeError, message).into()) - } - } -} - /// Restores the VM and aborts uncatchably, rolling back any armed OS effect. fn abort_restored( mut executor: Executor, @@ -1116,7 +1095,10 @@ pub(crate) fn convert_frame_exit(result: RunResult, vm: &mut VM<'_>) // `instruction_ip` still names the opcode that suspended, so the current // position is the suspending expression for every exit but `ResolveFutures`. match result { - Ok(FrameExit::Return(value)) => ConvertedExit::Complete(MontyObject::export(value, vm)), + Ok(FrameExit::Return(value)) => match vm.export_on_clock(|vm| MontyObject::export(value, vm)) { + Ok(obj) => ConvertedExit::Complete(obj), + Err(err) => ConvertedExit::Error(err), + }, Ok(FrameExit::ExternalCall { function_name, args, @@ -1125,14 +1107,16 @@ pub(crate) fn convert_frame_exit(result: RunResult, vm: &mut VM<'_>) }) => { let position = vm.suspension_position(); let name = function_name.into_string(vm.interns); - let args = args.into_call_args(vm); - ConvertedExit::FunctionCall { - function_name: name, - args, - call_id: call_id.raw(), - object_id: None, - allow_eager_await: vm.allow_eager_await(), - position, + match vm.export_on_clock(|vm| args.into_call_args(vm)) { + Ok(args) => ConvertedExit::FunctionCall { + function_name: name, + args, + call_id: call_id.raw(), + object_id: None, + allow_eager_await: vm.allow_eager_await(), + position, + }, + Err(err) => ConvertedExit::Error(err), } } Ok(FrameExit::OsCall { @@ -1161,14 +1145,16 @@ pub(crate) fn convert_frame_exit(result: RunResult, vm: &mut VM<'_>) }) => { let position = vm.suspension_position(); let name = method_name.into_string(vm.interns); - let args = args.into_call_args(vm); - ConvertedExit::FunctionCall { - function_name: name, - args, - call_id: call_id.raw(), - object_id: Some(object_id), - allow_eager_await: vm.allow_eager_await(), - position, + match vm.export_on_clock(|vm| args.into_call_args(vm)) { + Ok(args) => ConvertedExit::FunctionCall { + function_name: name, + args, + call_id: call_id.raw(), + object_id: Some(object_id), + allow_eager_await: vm.allow_eager_await(), + position, + }, + Err(err) => ConvertedExit::Error(err), } } Ok(FrameExit::ResolveFutures(pending_call_ids)) => ConvertedExit::ResolveFutures { diff --git a/crates/bashkit-monty/src/sorting.rs b/crates/bashkit-monty/src/sorting.rs deleted file mode 100644 index 371ec4abd..000000000 --- a/crates/bashkit-monty/src/sorting.rs +++ /dev/null @@ -1,171 +0,0 @@ -//! Shared sorting utilities for `sorted()` and `list.sort()`. -//! -//! Both `sorted()` and `list.sort()` use index-based sorting: they build -//! a vector of indices `[0, 1, 2, ...]`, sort the indices by comparing the -//! corresponding items (or key values), then rearrange items according to -//! the sorted indices. -//! -//! This module provides [`sort_indices`] for the comparison step and -//! [`apply_permutation`] for the in-place rearrangement step. - -use std::cmp::Ordering; - -use crate::{ - args::{ArgValues, FromArgs, LaxBool}, - bytecode::VM, - defer_drop, defer_drop_mut, - exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, - types::{CmpOrder, PyTrait}, - value::Value, -}; - -/// Argument shape for `list.sort(*, key=None, reverse=False)` and, by -/// extension, the kwargs accepted by the `sorted()` builtin. Both fields -/// are keyword-only (CPython rejects positional `key`/`reverse`). `key` is -/// held as a raw `Option` so callers can normalise `key=None` to -/// "no key"; `reverse` uses [`LaxBool`] to match CPython's `bool()`-style -/// truth test (so `reverse=[]` is `False`, not a `TypeError`). -#[derive(FromArgs)] -#[from_args(name = "sort")] -struct ListSortArgs { - #[from_args(kw_only, default)] - key: Option, - #[from_args(kw_only, default = LaxBool::new(false))] - reverse: LaxBool, -} - -/// Parses `key`/`reverse` kwargs and sorts `items` in place. The single -/// entry point for sorting used by both `list.sort` and the `sorted()` -/// builtin — sharing here is what makes unknown-kwarg errors uniformly -/// read `sort() got an unexpected keyword argument 'X'` (matching -/// CPython, whose `sorted` delegates to `list.sort` internally). -pub fn parse_and_sort(items: &mut [Value], args: ArgValues, vm: &mut VM<'_>) -> RunResult<()> { - let ListSortArgs { key, reverse } = ListSortArgs::from_args(args, vm)?; - let key_fn = match key { - Some(v) if matches!(v, Value::None) => { - v.drop_with(vm); - None - } - other => other, - }; - defer_drop!(key_fn, vm); - sort_values(items, key_fn.as_ref(), reverse.bool(), vm) -} - -/// Sorts a vector of values, with optional key function. -pub fn sort_values(values: &mut [Value], key_fn: Option<&Value>, reverse: bool, vm: &mut VM<'_>) -> RunResult<()> { - if let Some(f) = key_fn { - // Sort by key function: compute all the keys, sort an index buffer, then - // rearrange the original values in-place according to the sorted indices. - let mut indices = (0..values.len()).collect::>(); - let keys: Vec = Vec::with_capacity(values.len()); - defer_drop_mut!(keys, vm); - - // Each key call re-enters `run()` with a fresh dispatch countdown, so a - // short key reaches no checkpoint: this is the pass's only clock poll. - for (i, item) in values.iter().enumerate() { - vm.heap.tracker.check_time_every(i)?; - let item = item.clone_with_heap(vm); - keys.push(vm.evaluate_function(f, ArgValues::One(item))?); - } - - // 2. Sort indices by comparing key values (or values themselves if no key) - sort_indices(&mut indices, keys, reverse, vm)?; - - // 3. Rearrange values in-place in the detached buffer. - apply_permutation(values, &mut indices); - - Ok(()) - } else { - // With no key function can sort directly on the original array - let mut sort_result: RunResult<()> = Ok(()); - let mut n = 0usize; - values.sort_by(|a, b| { - n += 1; - compare_values(n, a, b, reverse, &mut sort_result, vm) - }); - sort_result - } -} - -/// Sorts a vector of indices by comparing items at those positions. -/// -/// Compares `values[a]` vs `values[b]` using `py_cmp`, optionally reversing -/// the ordering. If any comparison fails (type error or runtime error), the -/// sort finishes early and the error is returned. -/// -/// The `values` slice is typically either the items themselves (no key function) -/// or the pre-computed key values. -pub fn sort_indices(indices: &mut [usize], values: &[Value], reverse: bool, vm: &mut VM<'_>) -> Result<(), RunError> { - let mut sort_result: RunResult<()> = Ok(()); - let mut n = 0usize; - indices.sort_by(|&a, &b| { - n += 1; - compare_values(n, &values[a], &values[b], reverse, &mut sort_result, vm) - }); - sort_result -} - -/// Rearranges `items` in-place according to a permutation of indices. -/// -/// After calling this, `items[i]` will hold the element that was originally at -/// `items[indices[i]]`. The algorithm chases permutation cycles and swaps -/// elements into their final positions, using O(1) extra memory beyond the -/// `indices` slice (which is mutated to track visited positions). -/// -/// The helper is generic so callers can avoid allocating a second buffer when -/// reordering either raw `Value`s or compound structures that already own their -/// contents. Each element is moved at most twice (one swap = two moves), so -/// the total work is O(n) moves while preserving the target permutation. -pub fn apply_permutation(items: &mut [T], indices: &mut [usize]) { - for i in 0..items.len() { - if indices[i] == i { - continue; - } - let mut current = i; - loop { - let target = indices[current]; - indices[current] = current; - if target == i { - break; - } - items.swap(current, target); - current = target; - } - } -} - -/// Helper for the sort functions which compares two values, handling any exceptions and timeouts. -/// `n` is the caller's running comparison count, keying the amortized time check. -fn compare_values( - n: usize, - a: &Value, - b: &Value, - reverse: bool, - sort_result: &mut RunResult<()>, - vm: &mut VM<'_>, -) -> Ordering { - if sort_result.is_err() { - // short-circuit if we've already encountered an error in a previous comparison - return Ordering::Equal; - } - if let Err(e) = vm.heap.tracker.check_time_every(n) { - *sort_result = Err(e.into()); - return Ordering::Equal; - } - let err = match a.py_cmp(b, vm) { - Ok(CmpOrder::Ordered(ord)) => return if reverse { ord.reverse() } else { ord }, - // A `NaN` (or `NaN`-carrying container) has no ordering but must not - // raise: CPython's `sorted`/`list.sort` leave such elements wherever the - // comparisons happen to place them. Treat it as "equal" — no swap. - Ok(CmpOrder::Unordered) => return Ordering::Equal, - Ok(CmpOrder::Incomparable) => ExcType::type_error(format!( - "'<' not supported between instances of '{}' and '{}'", - a.py_type_name(vm), - b.py_type_name(vm) - )), - Err(e) => e, - }; - *sort_result = Err(err); - Ordering::Equal -} diff --git a/crates/bashkit-monty/src/sorting/mod.rs b/crates/bashkit-monty/src/sorting/mod.rs new file mode 100644 index 000000000..88cd70364 --- /dev/null +++ b/crates/bashkit-monty/src/sorting/mod.rs @@ -0,0 +1,356 @@ +//! Shared sorting utilities for `sorted()`, `list.sort()` and other sorts over Python values. +//! +//! Sorts use [`timsort`], a port of CPython's algorithm. Most are index-based: they build a vector of indices +//! `[0, 1, 2, ...]`, sort the indices by comparing the corresponding items (or key values), then rearrange the items +//! according to the sorted indices. Short lists without a key are sorted in place. +//! +//! Lists of plain numbers or of short strings skip the port: their `<` is a total order, so any stable sort leaves them +//! in CPython's order, and Rust's is faster. +//! +//! This module provides [`sort_indices`] and [`sort_indices_by`] for the comparison step and +//! [`apply_permutation`] for the in-place rearrangement step. + +mod timsort; + +use std::cmp::Ordering; + +use smallvec::SmallVec; +use timsort::{SortAborted, sort_short, timsort}; + +use crate::{ + args::{ArgValues, FromArgs, LaxBool}, + bytecode::VM, + defer_drop, defer_drop_mut, + exception_private::{RunError, RunResult}, + expressions::CmpOperator, + heap::HeapData, + types::{CmpOrder, PyTrait, long_int::i64_cmp_f64}, + value::Value, +}; + +/// Argument shape for `list.sort(*, key=None, reverse=False)` and, by +/// extension, the kwargs accepted by the `sorted()` builtin. Both fields +/// are keyword-only (CPython rejects positional `key`/`reverse`). `key` is +/// held as a raw `Option` so callers can normalise `key=None` to +/// "no key"; `reverse` uses [`LaxBool`] to match CPython's `bool()`-style +/// truth test (so `reverse=[]` is `False`, not a `TypeError`). +#[derive(FromArgs)] +#[from_args(name = "sort")] +struct ListSortArgs { + #[from_args(kw_only, default)] + key: Option, + #[from_args(kw_only, default = LaxBool::new(false))] + reverse: LaxBool, +} + +/// Parses `key`/`reverse` kwargs and sorts `items` in place. The single +/// entry point for sorting used by both `list.sort` and the `sorted()` +/// builtin — sharing here is what makes unknown-kwarg errors uniformly +/// read `sort() got an unexpected keyword argument 'X'` (matching +/// CPython, whose `sorted` delegates to `list.sort` internally). +pub fn parse_and_sort(items: &mut [Value], args: ArgValues, vm: &mut VM<'_>) -> RunResult<()> { + let ListSortArgs { key, reverse } = ListSortArgs::from_args(args, vm)?; + let key_fn = match key { + Some(v) if matches!(v, Value::None) => { + v.drop_with(vm); + None + } + other => other, + }; + defer_drop!(key_fn, vm); + sort_values(items, key_fn.as_ref(), reverse.bool(), vm) +} + +/// Sorts `values` in place, ordering by `key_fn(value)` when given, else by the values themselves. +/// +/// On a failed comparison the values are left partly sorted, as CPython leaves them. +pub fn sort_values(values: &mut [Value], key_fn: Option<&Value>, reverse: bool, vm: &mut VM<'_>) -> RunResult<()> { + if let Some(f) = key_fn { + let keys: Vec = Vec::with_capacity(values.len()); + defer_drop_mut!(keys, vm); + + // Each key call re-enters `run()` with a fresh dispatch countdown, so a + // short key reaches no checkpoint: this is the pass's only clock poll. + for (i, item) in values.iter().enumerate() { + vm.heap.tracker.check_time_every(i)?; + let item = item.clone_with_heap(vm); + keys.push(vm.evaluate_function(f, ArgValues::One(item))?); + } + let mut indices = identity_permutation(values.len()); + let result = sort_indices(&mut indices, keys, reverse, vm); + apply_permutation(values, &mut indices); + result + } else if let Some(order) = TotalOrder::of(values, vm) { + let vm: &VM<'_> = vm; + with_reversal(values, reverse, |values| { + values.sort_by(|a, b| order.cmp(a, b, vm)); + Ok(()) + }) + } else if values.len() < SHORT_SORT_LEN { + // Short lists need no merge, so the values are sorted where they are. + with_reversal(values, reverse, |values| { + let mut cmp = Comparer::new(vm); + let sorted = sort_short(values, |a, b| cmp.lt(|vm| py_lt(a, b, vm))); + cmp.finish(sorted) + }) + } else { + let mut indices = identity_permutation(values.len()); + let result = sort_indices(&mut indices, values, reverse, vm); + apply_permutation(values, &mut indices); + result + } +} + +/// Stably sorts `indices` so that `values[indices[0]], values[indices[1]], ...` ascend under Python's `<`. +/// +/// This is CPython's `list.sort`: the same algorithm making the same `<` calls, so input that is not totally +/// ordered (`NaN`, sets, comparisons that raise) ends in the same order and raises the same error. +/// `values` is typically the items themselves or their precomputed keys. +pub fn sort_indices(indices: &mut [usize], values: &[Value], reverse: bool, vm: &mut VM<'_>) -> Result<(), RunError> { + if let Some(order) = TotalOrder::of(values, vm) { + let vm: &VM<'_> = vm; + with_reversal(indices, reverse, |indices| { + indices.sort_by(|&a, &b| order.cmp(&values[a], &values[b], vm)); + Ok(()) + }) + } else { + sort_indices_by(indices, reverse, vm, |a, b, vm| py_lt(&values[a], &values[b], vm)) + } +} + +/// Stably sorts `indices` as CPython's `list.sort` would, with `lt(a, b)` standing in for `<` between the elements +/// that ids `a` and `b` name; for elements that are not plain values, such as CPython's `(key, order)` tuples. +pub fn sort_indices_by<'h>( + indices: &mut [usize], + reverse: bool, + vm: &mut VM<'h>, + mut lt: impl FnMut(usize, usize, &mut VM<'h>) -> RunResult, +) -> RunResult<()> { + with_reversal(indices, reverse, |indices| { + let mut cmp = Comparer::new(vm); + let sorted = timsort(indices, |a, b| cmp.lt(|vm| lt(a, b, vm))); + cmp.finish(sorted) + }) +} + +/// Lists shorter than this are sorted by [`sort_short`], without an index buffer. +const SHORT_SORT_LEN: usize = 64; + +/// The ids `0..len` in order, the starting point of an index sort; inline for the short lists most sorts see. +fn identity_permutation(len: usize) -> SmallVec<[usize; 32]> { + (0..len).collect() +} + +/// Runs `sort` with `items` reversed before and after when `reverse` is set, which is how CPython sorts in reverse +/// while keeping equal elements in their original order. The second reversal happens even when the sort fails. +fn with_reversal(items: &mut [T], reverse: bool, sort: impl FnOnce(&mut [T]) -> RunResult<()>) -> RunResult<()> { + if reverse { + items.reverse(); + } + let result = sort(items); + if reverse { + items.reverse(); + } + result +} + +/// Element kinds whose `<` is a total order that runs no user code and cannot raise. +/// +/// A stable sort under such an order has only one possible result, CPython's, and how many comparisons it made +/// cannot be observed, so these sorts may use Rust's faster `sort_by`. +#[derive(Clone, Copy)] +enum TotalOrder { + /// Every element is a [`Number`] other than `NaN`. + Numbers, + /// Every element is a `str` of at most [`MAX_FAST_STR_LEN`] bytes. + Strs, +} + +/// Longer strings sort through [`timsort`], whose comparisons poll the clock: `sort_by` cannot stop early, and +/// comparing many references to one long string would otherwise run unbounded work past the time limit. +const MAX_FAST_STR_LEN: usize = 256; + +impl TotalOrder { + /// The total order `values` share, if any: one pass over them before a sort. + fn of(values: &[Value], vm: &VM<'_>) -> Option { + let first = values.first()?; + if Number::of(first).is_some() { + let is_ordered = |v: &Value| Number::of(v).is_some_and(|n| !n.is_nan()); + values.iter().all(is_ordered).then_some(Self::Numbers) + } else { + let is_short = |v: &Value| str_of(v, vm).is_some_and(|s| s.len() <= MAX_FAST_STR_LEN); + values.iter().all(is_short).then_some(Self::Strs) + } + } + + /// Compares two elements of a list that [`TotalOrder::of`] accepted. + #[expect( + clippy::inline_always, + reason = "runs once per comparison; inlining it measurably speeds up sorts" + )] + #[inline(always)] + fn cmp(self, a: &Value, b: &Value, vm: &VM<'_>) -> Ordering { + // The `None`s cannot happen: `of` checked every element. + let ordering = match self { + Self::Numbers => Number::of(a).zip(Number::of(b)).and_then(|(a, b)| a.partial_cmp(b)), + Self::Strs => str_of(a, vm).zip(str_of(b, vm)).map(|(a, b)| a.cmp(b)), + }; + ordering.unwrap_or(Ordering::Equal) + } +} + +/// The comparison a sort makes, Python's `<`, with the sort's time checks. +/// +/// A failed comparison is kept here and the sort told only to stop, which keeps each comparison's result small. +struct Comparer<'v, 'h> { + vm: &'v mut VM<'h>, + /// Comparisons made so far, spacing the time checks. + count: usize, + error: Option, +} + +impl<'v, 'h> Comparer<'v, 'h> { + fn new(vm: &'v mut VM<'h>) -> Self { + Self { + vm, + count: 0, + error: None, + } + } + + /// Answers `a < b` by running `lt`, or stops the sort with the error stashed. + #[expect( + clippy::inline_always, + reason = "runs once per comparison; inlining it measurably speeds up sorts" + )] + #[inline(always)] + fn lt(&mut self, lt: impl FnOnce(&mut VM<'h>) -> RunResult) -> Result { + self.count += 1; + let lt = match self.vm.heap.tracker.check_time_every(self.count) { + Ok(()) => lt(self.vm), + Err(e) => Err(e.into()), + }; + lt.map_err(|e| { + self.error = Some(e); + SortAborted + }) + } + + /// Turns the sort's outcome back into the error that stopped it, if any. + fn finish(self, sorted: Result<(), SortAborted>) -> RunResult<()> { + sorted.map_err(|SortAborted| { + self.error + .expect("only `Comparer::lt` aborts a sort, and it stashes its error first") + }) + } +} + +/// Python's `a < b`, the only comparison the sort makes. +/// +/// Only heap values other than `str` can answer `<` themselves (sets, `Counter`, `Decimal`), so the rest skip +/// [`VM::cmp_values`]'s rich-comparison hooks; the common pairs are answered inline. +#[expect( + clippy::inline_always, + reason = "runs once per comparison; inlining it measurably speeds up sorts" +)] +#[inline(always)] +pub(crate) fn py_lt(a: &Value, b: &Value, vm: &mut VM<'_>) -> RunResult { + match (a, b) { + (Value::Int(a), Value::Int(b)) => Ok(a < b), + (Value::Float(a), Value::Float(b)) => Ok(a < b), + // A `NaN` operand is unordered, so `<` is `False`. + _ if let (Some(a), Some(b)) = (Number::of(a), Number::of(b)) => Ok(a.partial_cmp(b) == Some(Ordering::Less)), + _ if let (Some(a), Some(b)) = (str_of(a, vm), str_of(b, vm)) => Ok(a < b), + (Value::Ref(_), _) | (_, Value::Ref(_)) => vm.cmp_values(CmpOperator::Lt, a, b), + _ => match a.py_cmp(b, vm)? { + CmpOrder::Ordered(ordering) => Ok(ordering.is_lt()), + CmpOrder::Unordered => Ok(false), + // Raises CPython's `TypeError`. + CmpOrder::Incomparable => vm.cmp_values(CmpOperator::Lt, a, b), + }, + } +} + +/// Equality as CPython's tuple comparison asks it of an element pair, identity first. +/// +/// Numbers compare by value: Monty's immediate floats have no identity, so a `NaN` is never equal to another +/// (see `limitations/language.md`), where [`Value::py_eq`] would call two `NaN`s with the same bits identical. +pub(crate) fn py_eq_item(a: &Value, b: &Value, vm: &mut VM<'_>) -> RunResult { + match (Number::of(a), Number::of(b)) { + (Some(a), Some(b)) => Ok(a.partial_cmp(b) == Some(Ordering::Equal)), + _ => a.py_eq(b, vm), + } +} + +/// A number whose order needs no VM: an `int` that fits in `i64`, a `bool`, or a `float`. +#[derive(Clone, Copy)] +enum Number { + Int(i64), + Float(f64), +} + +impl Number { + fn of(value: &Value) -> Option { + match value { + Value::Int(i) => Some(Self::Int(*i)), + Value::Bool(b) => Some(Self::Int(i64::from(*b))), + Value::Float(f) => Some(Self::Float(*f)), + _ => None, + } + } + + fn is_nan(self) -> bool { + matches!(self, Self::Float(f) if f.is_nan()) + } + + /// Python's exact numeric order; `None` when either side is `NaN`. + fn partial_cmp(self, other: Self) -> Option { + match (self, other) { + (Self::Int(a), Self::Int(b)) => Some(a.cmp(&b)), + (Self::Float(a), Self::Float(b)) => a.partial_cmp(&b), + (Self::Int(a), Self::Float(b)) => i64_cmp_f64(a, b), + (Self::Float(a), Self::Int(b)) => i64_cmp_f64(b, a).map(Ordering::reverse), + } + } +} + +/// The text of a `str` value, interned or on the heap. +fn str_of<'a>(value: &Value, vm: &'a VM<'_>) -> Option<&'a str> { + match value { + Value::InternString(id) => Some(vm.interns.get_str(*id)), + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Str(s) => Some(s.as_str()), + _ => None, + }, + _ => None, + } +} + +/// Rearranges `items` in-place according to a permutation of indices. +/// +/// After calling this, `items[i]` will hold the element that was originally at +/// `items[indices[i]]`. The algorithm chases permutation cycles and swaps +/// elements into their final positions, using O(1) extra memory beyond the +/// `indices` slice (which is mutated to track visited positions). +/// +/// The helper is generic so callers can avoid allocating a second buffer when +/// reordering either raw `Value`s or compound structures that already own their +/// contents. Each element is moved at most twice (one swap = two moves), so +/// the total work is O(n) moves while preserving the target permutation. +pub fn apply_permutation(items: &mut [T], indices: &mut [usize]) { + for i in 0..items.len() { + if indices[i] == i { + continue; + } + let mut current = i; + loop { + let target = indices[current]; + indices[current] = current; + if target == i { + break; + } + items.swap(current, target); + current = target; + } + } +} diff --git a/crates/bashkit-monty/src/sorting/timsort.rs b/crates/bashkit-monty/src/sorting/timsort.rs new file mode 100644 index 000000000..e1e878bbb --- /dev/null +++ b/crates/bashkit-monty/src/sorting/timsort.rs @@ -0,0 +1,671 @@ +//! A port of CPython's `listsort` (`Objects/listobject.c`, 3.14): timsort with the powersort merge policy. +//! +//! Python comparisons need not be a total order (`NaN`, sets, comparisons that raise), and the order CPython leaves +//! such input in is observable. Porting the algorithm step for step, asking only `lt(a, b)` in the same sequence, +//! reproduces that order exactly, which no Rust std sort can do (and `slice::sort_by` panics on an inconsistent +//! comparator). +//! +//! The sort permutes `usize` element ids rather than the values, so merges can copy freely without `unsafe` or +//! refcount traffic; [`sort_short`] moves the values themselves when no merge is needed. A failed comparison stops +//! the sort at once; like CPython, the ids are still a permutation of the input when the error is returned, so +//! callers may apply them either way. + +use std::{cmp::min, mem}; + +/// When a merge enters galloping mode it stays there until both runs win fewer than this many times in a row. +const MIN_GALLOP: usize = 7; + +/// Upper bound of the minimum run length; a power of two, as `merge_compute_minrun` requires. +const MAX_MINRUN: usize = 64; + +/// Returned by the comparison to stop the sort; the caller keeps the actual error. +/// +/// Zero-sized so a comparison's result fits in a register: comparisons dominate the sort's cost. +#[derive(Clone, Copy)] +pub(super) struct SortAborted; + +/// Sorts `ids` stably, ordering by `lt`, which is called with two element ids and answers "is the first less than +/// the second". The first [`SortAborted`] from `lt` aborts the sort; `ids` is then some permutation of its input. +pub(super) fn timsort( + ids: &mut [usize], + lt: impl FnMut(usize, usize) -> Result, +) -> Result<(), SortAborted> { + let list_len = ids.len(); + if list_len < 2 { + return Ok(()); + } + let mut state = MergeState { + lt, + min_gallop: MIN_GALLOP, + tmp: Vec::new(), + pending: Vec::new(), + list_len, + }; + let minrun = merge_compute_minrun(list_len); + let mut lo = 0; + while lo < list_len { + let remaining = list_len - lo; + let lt = &mut |x: &usize, y: &usize| (state.lt)(*x, *y); + let mut n = count_run(&mut ids[lo..], lt)?; + // Extend a short natural run to `minrun` with binary insertion. + if n < minrun { + let force = min(remaining, minrun); + binary_sort(&mut ids[lo..lo + force], n, lt)?; + n = force; + } + state.found_new_run(ids, n)?; + state.pending.push(Run { + base: lo, + len: n, + power: 0, + }); + lo += n; + } + state.merge_force_collapse(ids) +} + +/// Sorts a slice shorter than 64 elements in place, exactly as [`timsort`] would sort ids for it. +/// +/// Below 64 elements CPython's sort is one natural run extended by binary insertion, with no merge, so it needs no +/// scratch copies and can move the values themselves; that spares short sorts the id buffer. +pub(super) fn sort_short( + a: &mut [T], + mut lt: impl FnMut(&T, &T) -> Result, +) -> Result<(), SortAborted> { + debug_assert!(a.len() < MAX_MINRUN); + if a.len() < 2 { + return Ok(()); + } + let n = count_run(a, &mut lt)?; + if n < a.len() { + binary_sort(a, n, &mut lt)?; + } + Ok(()) +} + +/// Stable binary insertion sort of `a`, whose first `ok` elements are already sorted. +fn binary_sort( + a: &mut [T], + ok: usize, + lt: &mut impl FnMut(&T, &T) -> Result, +) -> Result<(), SortAborted> { + for ok in ok.max(1)..a.len() { + let (mut l, mut r) = (0, ok); + while l < r { + let m = usize::midpoint(l, r); + if lt(&a[ok], &a[m])? { + r = m; + } else { + l = m + 1; + } + } + a[l..=ok].rotate_right(1); + } + Ok(()) +} + +/// Returns the length of the run at the start of `a`, reversing it in place first if it is descending. +/// +/// A descending run may contain equal neighbours; each such group is reversed on the fly so the final +/// whole-run reversal restores their original order, keeping the sort stable. +fn count_run(a: &mut [T], lt: &mut impl FnMut(&T, &T) -> Result) -> Result { + let remaining = a.len(); + let mut n = 1; + // Try an ascending run first. + while n < remaining && !lt(&a[n], &a[n - 1])? { + n += 1; + } + if n == remaining { + return Ok(n); + } + // `a[n]` is strictly less. If the ascending prefix rose anywhere, it is the run; otherwise its elements are + // all equal, and it starts a descending run. + if n > 1 { + if lt(&a[0], &a[n - 1])? { + return Ok(n); + } + a[..n].reverse(); + } + n += 1; + + // Finish the descending run; `neq` counts the trailing equal neighbours seen so far. + let mut neq = 0; + while n < remaining { + if lt(&a[n], &a[n - 1])? { + reverse_last_equal(a, n, &mut neq); + } else if lt(&a[n - 1], &a[n])? { + break; + } else { + neq += 1; + } + n += 1; + } + reverse_last_equal(a, n, &mut neq); + a[..n].reverse(); + + // The reversed run may continue with an ascending suffix, e.g. `[3, 2, 3, 4, 1]`. + while n < remaining && !lt(&a[n], &a[n - 1])? { + n += 1; + } + Ok(n) +} + +/// A sorted run awaiting a merge: `ids[base..base + len]`. +#[derive(Clone, Copy)] +struct Run { + base: usize, + len: usize, + /// The powersort node level separating this run from the next one. + power: u32, +} + +/// What `merge_lo` / `merge_hi` do once their main loop stops. +enum MergeEnd { + /// Copy the remaining scratch elements back into place. + Drain, + /// One element of the scratch run is left; it goes after (or before) the rest of the other run. + CopyLast, +} + +/// State shared by one sort's helpers, mirroring CPython's `MergeState`. +struct MergeState { + lt: F, + /// Adaptive galloping threshold, nudged by each merge. + min_gallop: usize, + /// Scratch space holding the smaller run while it is merged. + tmp: Vec, + /// Stack of runs yet to be merged; adjacent entries are adjacent in `ids`. + pending: Vec, + list_len: usize, +} + +impl Result> MergeState { + /// Records a new run of length `n2` after the top of the stack, first merging any pending runs whose powersort + /// level is deeper than the boundary the new run creates. + fn found_new_run(&mut self, ids: &mut [usize], n2: usize) -> Result<(), SortAborted> { + let Some(last) = self.pending.last() else { + return Ok(()); + }; + let power = powerloop(last.base, last.len, n2, self.list_len); + while self.pending.len() > 1 && self.pending[self.pending.len() - 2].power > power { + self.merge_at(ids, self.pending.len() - 2)?; + } + let top = self.pending.len() - 1; + self.pending[top].power = power; + Ok(()) + } + + /// Merges every pending run, leaving one. + fn merge_force_collapse(&mut self, ids: &mut [usize]) -> Result<(), SortAborted> { + while self.pending.len() > 1 { + let mut n = self.pending.len() - 2; + if n > 0 && self.pending[n - 1].len < self.pending[n + 1].len { + n -= 1; + } + self.merge_at(ids, n)?; + } + Ok(()) + } + + /// Merges the pending runs at stack indices `i` and `i + 1`. + fn merge_at(&mut self, ids: &mut [usize], i: usize) -> Result<(), SortAborted> { + let Run { + base: mut base_a, + len: mut na, + .. + } = self.pending[i]; + let Run { + base: base_b, len: nb, .. + } = self.pending[i + 1]; + self.pending[i].len = na + nb; + if i + 3 == self.pending.len() { + self.pending[i + 1] = self.pending[i + 2]; + } + self.pending.pop(); + + // Elements of A before where B's first element belongs are already in place. + let k = self.gallop_right(ids[base_b], &ids[base_a..base_a + na], 0)?; + base_a += k; + na -= k; + if na == 0 { + return Ok(()); + } + // Likewise elements of B after where A's last element belongs. + let nb = self.gallop_left(ids[base_a + na - 1], &ids[base_b..base_b + nb], nb - 1)?; + if nb == 0 { + return Ok(()); + } + if na <= nb { + self.merge_lo(ids, base_a, na, nb) + } else { + self.merge_hi(ids, base_a, na, nb) + } + } + + /// Returns `k` such that `a[k - 1] < key <= a[k]`: where `key` goes, left of any equal elements. + /// + /// The search gallops outwards from `hint` before binary searching, so a good hint makes it cheap. + fn gallop_left(&mut self, key: usize, a: &[usize], hint: usize) -> Result { + let n = a.len(); + let mut last_ofs = 0; + let mut ofs = 1; + let (mut lo, hi) = if (self.lt)(a[hint], key)? { + // a[hint] < key: gallop right until a[hint + last_ofs] < key <= a[hint + ofs]. + let max_ofs = n - hint; + while ofs < max_ofs { + if (self.lt)(a[hint + ofs], key)? { + last_ofs = ofs; + ofs = (ofs << 1) + 1; + } else { + break; + } + } + // `lo` is one past an index known to be < key. + (hint + last_ofs + 1, hint + min(ofs, max_ofs)) + } else { + // key <= a[hint]: gallop left until a[hint - ofs] < key <= a[hint - last_ofs]. + let max_ofs = hint + 1; + while ofs < max_ofs { + if (self.lt)(a[hint - ofs], key)? { + break; + } + last_ofs = ofs; + ofs = (ofs << 1) + 1; + } + // CPython's `lastofs` may be -1 here; this is it plus one. + (hint + 1 - min(ofs, max_ofs), hint - last_ofs) + }; + let mut hi = hi; + while lo < hi { + let m = lo + ((hi - lo) >> 1); + if (self.lt)(a[m], key)? { + lo = m + 1; + } else { + hi = m; + } + } + Ok(hi) + } + + /// Returns `k` such that `a[k - 1] <= key < a[k]`: where `key` goes, right of any equal elements. + fn gallop_right(&mut self, key: usize, a: &[usize], hint: usize) -> Result { + let n = a.len(); + let mut last_ofs = 0; + let mut ofs = 1; + let (mut lo, hi) = if (self.lt)(key, a[hint])? { + // key < a[hint]: gallop left until a[hint - ofs] <= key < a[hint - last_ofs]. + let max_ofs = hint + 1; + while ofs < max_ofs { + if (self.lt)(key, a[hint - ofs])? { + last_ofs = ofs; + ofs = (ofs << 1) + 1; + } else { + break; + } + } + (hint + 1 - min(ofs, max_ofs), hint - last_ofs) + } else { + // a[hint] <= key: gallop right until a[hint + last_ofs] <= key < a[hint + ofs]. + let max_ofs = n - hint; + while ofs < max_ofs { + if (self.lt)(key, a[hint + ofs])? { + break; + } + last_ofs = ofs; + ofs = (ofs << 1) + 1; + } + (hint + last_ofs + 1, hint + min(ofs, max_ofs)) + }; + let mut hi = hi; + while lo < hi { + let m = lo + ((hi - lo) >> 1); + if (self.lt)(key, a[m])? { + hi = m; + } else { + lo = m + 1; + } + } + Ok(hi) + } + + /// Merges run A (`ids[base_a..base_a + na]`) with the run B that follows it, copying A to scratch and filling + /// from the left. Used when `na <= nb`; requires A's first element to belong first and B's last to belong last. + fn merge_lo(&mut self, ids: &mut [usize], base_a: usize, na: usize, nb: usize) -> Result<(), SortAborted> { + self.tmp.clear(); + self.tmp.extend_from_slice(&ids[base_a..base_a + na]); + let mut cur = LoCursor { + dest: base_a, + pa: 0, + pb: base_a + na, + na, + nb, + }; + let result = self.merge_lo_loop(ids, &mut cur); + let LoCursor { dest, pa, pb, na, nb } = cur; + match result { + Ok(MergeEnd::CopyLast) => { + // The last element of A belongs after everything left in B. + ids.copy_within(pb..pb + nb, dest); + ids[dest + nb] = self.tmp[pa]; + Ok(()) + } + // Success or failure, whatever is left of A goes back so `ids` stays a permutation. + other => { + ids[dest..dest + na].copy_from_slice(&self.tmp[pa..pa + na]); + other.map(drop) + } + } + } + + /// The body of [`merge_lo`](Self::merge_lo), split out so `?` can stop it while the caller tidies up. + fn merge_lo_loop(&mut self, ids: &mut [usize], c: &mut LoCursor) -> Result { + ids[c.dest] = ids[c.pb]; + c.dest += 1; + c.pb += 1; + c.nb -= 1; + if c.nb == 0 { + return Ok(MergeEnd::Drain); + } + if c.na == 1 { + return Ok(MergeEnd::CopyLast); + } + let mut min_gallop = self.min_gallop; + loop { + // Straightforward merge until one run wins `min_gallop` times in a row. + let mut acount = 0; + let mut bcount = 0; + loop { + if (self.lt)(ids[c.pb], self.tmp[c.pa])? { + ids[c.dest] = ids[c.pb]; + c.dest += 1; + c.pb += 1; + bcount += 1; + acount = 0; + c.nb -= 1; + if c.nb == 0 { + return Ok(MergeEnd::Drain); + } + if bcount >= min_gallop { + break; + } + } else { + ids[c.dest] = self.tmp[c.pa]; + c.dest += 1; + c.pa += 1; + acount += 1; + bcount = 0; + c.na -= 1; + if c.na == 1 { + return Ok(MergeEnd::CopyLast); + } + if acount >= min_gallop { + break; + } + } + } + + // Gallop until neither run is winning consistently. + min_gallop += 1; + loop { + min_gallop -= usize::from(min_gallop > 1); + self.min_gallop = min_gallop; + let k = self.gallop_right_tmp(ids[c.pb], c.pa, c.na)?; + acount = k; + if k > 0 { + ids[c.dest..c.dest + k].copy_from_slice(&self.tmp[c.pa..c.pa + k]); + c.dest += k; + c.pa += k; + c.na -= k; + if c.na == 1 { + return Ok(MergeEnd::CopyLast); + } + // Only reachable with an inconsistent comparison. + if c.na == 0 { + return Ok(MergeEnd::Drain); + } + } + ids[c.dest] = ids[c.pb]; + c.dest += 1; + c.pb += 1; + c.nb -= 1; + if c.nb == 0 { + return Ok(MergeEnd::Drain); + } + + let k = self.gallop_left(self.tmp[c.pa], &ids[c.pb..c.pb + c.nb], 0)?; + bcount = k; + if k > 0 { + ids.copy_within(c.pb..c.pb + k, c.dest); + c.dest += k; + c.pb += k; + c.nb -= k; + if c.nb == 0 { + return Ok(MergeEnd::Drain); + } + } + ids[c.dest] = self.tmp[c.pa]; + c.dest += 1; + c.pa += 1; + c.na -= 1; + if c.na == 1 { + return Ok(MergeEnd::CopyLast); + } + if acount < MIN_GALLOP && bcount < MIN_GALLOP { + break; + } + } + // Penalise leaving galloping mode. + min_gallop += 1; + self.min_gallop = min_gallop; + } + } + + /// Merges run A (`ids[base_a..base_a + na]`) with the run B of length `nb` that follows it, copying B to scratch + /// and filling from the right. Used when `na > nb`; same preconditions as [`merge_lo`](Self::merge_lo). + fn merge_hi(&mut self, ids: &mut [usize], base_a: usize, na: usize, nb: usize) -> Result<(), SortAborted> { + let base_b = base_a + na; + self.tmp.clear(); + self.tmp.extend_from_slice(&ids[base_b..base_b + nb]); + // Cursors point one past the next element to move, so they never go below zero. + let mut cur = HiCursor { + dest: base_b + nb, + pa: base_b, + pb: nb, + na, + nb, + }; + let result = self.merge_hi_loop(ids, base_a, &mut cur); + let HiCursor { dest, pa, nb, na, .. } = cur; + match result { + Ok(MergeEnd::CopyLast) => { + // The first element of B belongs before everything left in A. + ids.copy_within(pa - na..pa, dest - na); + ids[dest - na - 1] = self.tmp[0]; + Ok(()) + } + other => { + ids[dest - nb..dest].copy_from_slice(&self.tmp[..nb]); + other.map(drop) + } + } + } + + /// The body of [`merge_hi`](Self::merge_hi), split out so `?` can stop it while the caller tidies up. + fn merge_hi_loop(&mut self, ids: &mut [usize], base_a: usize, c: &mut HiCursor) -> Result { + c.dest -= 1; + c.pa -= 1; + ids[c.dest] = ids[c.pa]; + c.na -= 1; + if c.na == 0 { + return Ok(MergeEnd::Drain); + } + if c.nb == 1 { + return Ok(MergeEnd::CopyLast); + } + let mut min_gallop = self.min_gallop; + loop { + let mut acount = 0; + let mut bcount = 0; + loop { + if (self.lt)(self.tmp[c.pb - 1], ids[c.pa - 1])? { + c.dest -= 1; + c.pa -= 1; + ids[c.dest] = ids[c.pa]; + acount += 1; + bcount = 0; + c.na -= 1; + if c.na == 0 { + return Ok(MergeEnd::Drain); + } + if acount >= min_gallop { + break; + } + } else { + c.dest -= 1; + c.pb -= 1; + ids[c.dest] = self.tmp[c.pb]; + bcount += 1; + acount = 0; + c.nb -= 1; + if c.nb == 1 { + return Ok(MergeEnd::CopyLast); + } + if bcount >= min_gallop { + break; + } + } + } + + min_gallop += 1; + loop { + min_gallop -= usize::from(min_gallop > 1); + self.min_gallop = min_gallop; + let k = c.na - self.gallop_right(self.tmp[c.pb - 1], &ids[base_a..base_a + c.na], c.na - 1)?; + acount = k; + if k > 0 { + c.dest -= k; + c.pa -= k; + ids.copy_within(c.pa..c.pa + k, c.dest); + c.na -= k; + if c.na == 0 { + return Ok(MergeEnd::Drain); + } + } + c.dest -= 1; + c.pb -= 1; + ids[c.dest] = self.tmp[c.pb]; + c.nb -= 1; + if c.nb == 1 { + return Ok(MergeEnd::CopyLast); + } + + let k = c.nb - self.gallop_left_tmp(ids[c.pa - 1], c.nb)?; + bcount = k; + if k > 0 { + c.dest -= k; + c.pb -= k; + ids[c.dest..c.dest + k].copy_from_slice(&self.tmp[c.pb..c.pb + k]); + c.nb -= k; + if c.nb == 1 { + return Ok(MergeEnd::CopyLast); + } + // Only reachable with an inconsistent comparison. + if c.nb == 0 { + return Ok(MergeEnd::Drain); + } + } + c.dest -= 1; + c.pa -= 1; + ids[c.dest] = ids[c.pa]; + c.na -= 1; + if c.na == 0 { + return Ok(MergeEnd::Drain); + } + if acount < MIN_GALLOP && bcount < MIN_GALLOP { + break; + } + } + min_gallop += 1; + self.min_gallop = min_gallop; + } + } + + /// [`gallop_right`](Self::gallop_right) over `tmp[start..start + len]` with hint 0, taking `tmp` out so the + /// comparator can be borrowed alongside it. + fn gallop_right_tmp(&mut self, key: usize, start: usize, len: usize) -> Result { + let tmp = mem::take(&mut self.tmp); + let result = self.gallop_right(key, &tmp[start..start + len], 0); + self.tmp = tmp; + result + } + + /// [`gallop_left`](Self::gallop_left) over `tmp[..len]` with hint `len - 1`; see + /// [`gallop_right_tmp`](Self::gallop_right_tmp). + fn gallop_left_tmp(&mut self, key: usize, len: usize) -> Result { + let tmp = mem::take(&mut self.tmp); + let result = self.gallop_left(key, &tmp[..len], len - 1); + self.tmp = tmp; + result + } +} + +/// Positions within [`MergeState::merge_lo`], named after CPython's locals (`pa`/`pb` are its `ssa`/`ssb`): +/// `pa` indexes scratch (run A), `dest` and `pb` index `ids`. +struct LoCursor { + dest: usize, + pa: usize, + pb: usize, + na: usize, + nb: usize, +} + +/// Positions within [`MergeState::merge_hi`], named as in [`LoCursor`]: `pb` indexes scratch (run B), `dest` and +/// `pa` index `ids`. Each sits one past the next element, where CPython's pointers sit on it. +struct HiCursor { + dest: usize, + pa: usize, + pb: usize, + na: usize, + nb: usize, +} + +/// Reverses the group of `*neq + 1` equal elements ending just before `a[n]`, if there is one, and resets `*neq`. +fn reverse_last_equal(a: &mut [T], n: usize, neq: &mut usize) { + if *neq > 0 { + let len = *neq + 1; + a[n - len..n].reverse(); + *neq = 0; + } +} + +/// Returns the powersort level of the boundary between adjacent runs `[s1, s1 + n1)` and `[s1 + n1, s1 + n1 + n2)` +/// in a list of length `n`: the first bit at which the scaled midpoints of the two runs differ. +fn powerloop(s1: usize, n1: usize, n2: usize, n: usize) -> u32 { + let mut result = 0; + // Twice the midpoints, so they stay integers. + let mut a = 2 * s1 + n1; + let mut b = a + n1 + n2; + loop { + result += 1; + if a >= n { + a -= n; + b -= n; + } else if b >= n { + break; + } + a <<= 1; + b <<= 1; + } + result +} + +/// Picks a minimum run length in `32..=64` (or `n` itself when smaller) so `n / minrun` is a power of two or just +/// under one, which keeps the final merges balanced. +fn merge_compute_minrun(mut n: usize) -> usize { + let mut r = 0; + while n >= MAX_MINRUN { + r |= n & 1; + n >>= 1; + } + n + r +} diff --git a/crates/bashkit-monty/src/source_map.rs b/crates/bashkit-monty/src/source_map.rs index bcd038314..eccc60836 100644 --- a/crates/bashkit-monty/src/source_map.rs +++ b/crates/bashkit-monty/src/source_map.rs @@ -141,7 +141,9 @@ impl<'s> SourceMap<'s> { let line_idx = self.line_starts.partition_point(|&s| s <= byte).saturating_sub(1); let line_start = self.line_starts[line_idx]; let slice_start = line_start as usize; - let slice_end = (byte as usize).min(self.source.len()); + // Positions from an older dump can be misaligned with their source + // (see `dump_upgrade`), so an offset inside a character rounds down. + let slice_end = self.source.floor_char_boundary(byte as usize); let slice = &self.source[slice_start..slice_end]; // Ruff caps source files at 4 GiB, so any byte-based column count fits // comfortably in `u32`; saturate defensively if that ever changes. diff --git a/crates/bashkit-monty/src/str_format.rs b/crates/bashkit-monty/src/str_format.rs index 73189b380..7816747d3 100644 --- a/crates/bashkit-monty/src/str_format.rs +++ b/crates/bashkit-monty/src/str_format.rs @@ -374,7 +374,7 @@ fn resolve_positional(index: usize, arguments: &FormatArguments, vm: &VM<'_>) -> fn resolve_keyword(name: &str, arguments: &FormatArguments, vm: &mut VM<'_>) -> RunResult { for (index, (key, value)) in arguments.keywords.iter().enumerate() { vm.heap.tracker.check_time_every(index)?; - if key.to_str(vm)? == name { + if key.as_str(vm).expect("keyword names are validated by the binder") == name { return Ok(value.clone_with_heap(vm.heap)); } } diff --git a/crates/bashkit-monty/src/stringize.rs b/crates/bashkit-monty/src/stringize.rs index 3dacf7c0b..b56bea42c 100644 --- a/crates/bashkit-monty/src/stringize.rs +++ b/crates/bashkit-monty/src/stringize.rs @@ -1,11 +1,11 @@ //! Rendering a ruff AST expression back to source text, the way CPython's //! PEP 563 stringizer does. //! -//! The inverse of [`parse`](crate::parse). Class annotations are the only caller -//! today (they are stored stringized, not evaluated — see -//! `limitations/typing.md`), but the contract is "match CPython's stringizer", so -//! any future stringization belongs here. Unparsing rather than slicing the -//! source is what makes `x: dict[str,int]` yield `'dict[str, int]'` on both. +//! The inverse of [`parse`](crate::parse). Annotations under +//! `from __future__ import annotations` are the only caller today, but the +//! contract is "match CPython's stringizer", so any future stringization belongs +//! here. Unparsing rather than slicing the source is what makes +//! `x: dict[str,int]` yield `'dict[str, int]'` on both. use ruff_python_ast::{ self as ast, AtomicNodeIndex, Expr as AstExpr, diff --git a/crates/bashkit-monty/src/types/builtin_type.rs b/crates/bashkit-monty/src/types/builtin_type.rs new file mode 100644 index 000000000..564f05633 --- /dev/null +++ b/crates/bashkit-monty/src/types/builtin_type.rs @@ -0,0 +1,554 @@ +use std::fmt; + +use crate::{exception_private::ExcType, types::Type}; + +/// Type objects stored inline in values; user classes use heap references. +/// Serialize through `Type` to retain its dump names and postcard indices, +/// including the gap left by `Type::Instance`. Keep both conversions exhaustive. +#[derive( + Debug, + Clone, + Copy, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, + strum::EnumString, + strum::IntoStaticStr, + strum::VariantNames, +)] +#[strum(serialize_all = "lowercase")] +#[serde(into = "Type", try_from = "Type")] +pub(crate) enum BuiltinType { + Ellipsis, + #[strum(serialize = "NotImplementedType")] + NotImplementedType, + Type, + #[strum(serialize = "NoneType")] + NoneType, + Bool, + Int, + Float, + Complex, + Range, + Slice, + #[strum(serialize = "datetime.date")] + Date, + #[strum(serialize = "datetime.datetime")] + DateTime, + #[strum(serialize = "datetime.timedelta")] + TimeDelta, + #[strum(serialize = "datetime.timezone")] + TimeZone, + Str, + Bytes, + List, + Tuple, + NamedTuple, + Dict, + #[strum(serialize = "collections.defaultdict")] + DefaultDict, + #[strum(serialize = "Counter")] + Counter, + #[strum(serialize = "dict_keys")] + DictKeys, + #[strum(serialize = "dict_items")] + DictItems, + #[strum(serialize = "dict_values")] + DictValues, + Set, + FrozenSet, + #[strum(serialize = "HostClass")] + HostClass, + #[strum(disabled)] + Exception(ExcType), + Function, + #[strum(serialize = "builtin_function_or_method")] + BuiltinFunction, + Cell, + Iterator, + #[strum(serialize = "list_iterator")] + ListIterator, + #[strum(serialize = "callable_iterator")] + CallableIterator, + Coroutine, + Module, + #[strum(serialize = "_io.TextIOWrapper")] + TextIOWrapper, + #[strum(serialize = "_io.BufferedReader")] + BufferedReader, + #[strum(serialize = "_io.BufferedWriter")] + BufferedWriter, + #[strum(serialize = "_io.BufferedRandom")] + BufferedRandom, + #[strum(serialize = "typing._SpecialForm")] + SpecialForm, + #[strum(serialize = "PosixPath")] + Path, + Property, + #[strum(serialize = "re.Pattern")] + RePattern, + #[strum(serialize = "re.Match")] + ReMatch, + #[strum(serialize = "posix.DirEntry")] + DirEntry, + #[strum(serialize = "posix.ScandirIterator")] + ScandirIterator, + #[strum(serialize = "generator")] + WalkGenerator, + #[strum(serialize = "tuple_iterator")] + TupleIterator, + #[strum(serialize = "str_ascii_iterator")] + StrAsciiIterator, + #[strum(serialize = "str_iterator")] + StrIterator, + #[strum(serialize = "bytes_iterator")] + BytesIterator, + #[strum(serialize = "range_iterator")] + RangeIterator, + #[strum(serialize = "dict_keyiterator")] + DictKeyIterator, + #[strum(serialize = "dict_itemiterator")] + DictItemIterator, + #[strum(serialize = "dict_valueiterator")] + DictValueIterator, + #[strum(serialize = "set_iterator")] + SetIterator, + #[strum(serialize = "itertools.count")] + ItertoolsCount, + #[strum(serialize = "itertools.repeat")] + ItertoolsRepeat, + #[strum(serialize = "Field")] + DataclassField, + #[strum(serialize = "collections.deque")] + Deque, + #[strum(serialize = "_collections._deque_iterator")] + DequeIterator, + #[strum(serialize = "itertools.pairwise")] + ItertoolsPairwise, + #[strum(serialize = "itertools.compress")] + ItertoolsCompress, + #[strum(serialize = "itertools.islice")] + ItertoolsIslice, + #[strum(serialize = "itertools.chain")] + ItertoolsChain, + #[strum(serialize = "itertools.cycle")] + ItertoolsCycle, + #[strum(serialize = "_DataclassParams")] + DataclassParams, + #[strum(serialize = "dataclasses._MISSING_TYPE")] + MissingType, + #[strum(serialize = "itertools.takewhile")] + ItertoolsTakeWhile, + #[strum(serialize = "itertools.dropwhile")] + ItertoolsDropWhile, + #[strum(serialize = "itertools.filterfalse")] + ItertoolsFilterFalse, + #[strum(serialize = "itertools.starmap")] + ItertoolsStarMap, + Object, + #[strum(serialize = "datetime.time")] + Time, + #[strum(serialize = "functools.partial")] + Partial, + #[strum(serialize = "itertools.accumulate")] + ItertoolsAccumulate, + #[strum(serialize = "itertools.batched")] + ItertoolsBatched, + #[strum(serialize = "itertools.zip_longest")] + ItertoolsZipLongest, + #[strum(serialize = "types.GenericAlias")] + GenericAlias, + #[strum(serialize = "typing.Union")] + Union, + #[strum(serialize = "itertools.combinations")] + ItertoolsCombinations, + #[strum(serialize = "itertools.combinations_with_replacement")] + ItertoolsCombinationsWithReplacement, + #[strum(serialize = "itertools.permutations")] + ItertoolsPermutations, + #[strum(serialize = "itertools.product")] + ItertoolsProduct, + #[strum(serialize = "itertools.groupby")] + ItertoolsGroupBy, + #[strum(serialize = "itertools._grouper")] + ItertoolsGrouper, + #[strum(serialize = "itertools._tee")] + ItertoolsTee, + #[strum(serialize = "itertools._tee_dataobject")] + ItertoolsTeeDataObject, + #[strum(serialize = "random.Random")] + Random, + #[strum(serialize = "functools._lru_cache_wrapper")] + LruCacheWrapper, + #[strum(serialize = "_hashlib.HASH")] + HashlibHash, + #[strum(serialize = "_hashlib.HASHXOF")] + HashlibHashXof, + #[strum(serialize = "_blake2.blake2b")] + Blake2b, + #[strum(serialize = "_blake2.blake2s")] + Blake2s, + #[strum(serialize = "_csv.reader")] + CsvReader, + #[strum(serialize = "_csv.writer")] + CsvWriter, + #[strum(serialize = "csv.DictReader")] + CsvDictReader, + #[strum(serialize = "csv.DictWriter")] + CsvDictWriter, + #[strum(serialize = "_csv.Dialect")] + CsvDialect, + #[strum(serialize = "decimal.Decimal")] + Decimal, + #[strum(serialize = "decimal.Context")] + DecimalContext, + #[strum(serialize = "SignalDict")] + DecimalSignalDict, + #[strum(serialize = "decimal.ContextManager")] + DecimalContextManager, + #[strum(serialize = "annotationlib.ForwardRef")] + ForwardRef, +} + +impl From for Type { + fn from(value: BuiltinType) -> Self { + match value { + BuiltinType::Ellipsis => Self::Ellipsis, + BuiltinType::NotImplementedType => Self::NotImplementedType, + BuiltinType::Type => Self::Type, + BuiltinType::NoneType => Self::NoneType, + BuiltinType::Bool => Self::Bool, + BuiltinType::Int => Self::Int, + BuiltinType::Float => Self::Float, + BuiltinType::Complex => Self::Complex, + BuiltinType::Range => Self::Range, + BuiltinType::Slice => Self::Slice, + BuiltinType::Date => Self::Date, + BuiltinType::DateTime => Self::DateTime, + BuiltinType::TimeDelta => Self::TimeDelta, + BuiltinType::TimeZone => Self::TimeZone, + BuiltinType::Str => Self::Str, + BuiltinType::Bytes => Self::Bytes, + BuiltinType::List => Self::List, + BuiltinType::Tuple => Self::Tuple, + BuiltinType::NamedTuple => Self::NamedTuple, + BuiltinType::Dict => Self::Dict, + BuiltinType::DefaultDict => Self::DefaultDict, + BuiltinType::Counter => Self::Counter, + BuiltinType::DictKeys => Self::DictKeys, + BuiltinType::DictItems => Self::DictItems, + BuiltinType::DictValues => Self::DictValues, + BuiltinType::Set => Self::Set, + BuiltinType::FrozenSet => Self::FrozenSet, + BuiltinType::HostClass => Self::HostClass, + BuiltinType::Exception(exc_type) => Self::Exception(exc_type), + BuiltinType::Function => Self::Function, + BuiltinType::BuiltinFunction => Self::BuiltinFunction, + BuiltinType::Cell => Self::Cell, + BuiltinType::Iterator => Self::Iterator, + BuiltinType::ListIterator => Self::ListIterator, + BuiltinType::CallableIterator => Self::CallableIterator, + BuiltinType::Coroutine => Self::Coroutine, + BuiltinType::Module => Self::Module, + BuiltinType::TextIOWrapper => Self::TextIOWrapper, + BuiltinType::BufferedReader => Self::BufferedReader, + BuiltinType::BufferedWriter => Self::BufferedWriter, + BuiltinType::BufferedRandom => Self::BufferedRandom, + BuiltinType::SpecialForm => Self::SpecialForm, + BuiltinType::Path => Self::Path, + BuiltinType::Property => Self::Property, + BuiltinType::RePattern => Self::RePattern, + BuiltinType::ReMatch => Self::ReMatch, + BuiltinType::DirEntry => Self::DirEntry, + BuiltinType::ScandirIterator => Self::ScandirIterator, + BuiltinType::WalkGenerator => Self::WalkGenerator, + BuiltinType::TupleIterator => Self::TupleIterator, + BuiltinType::StrAsciiIterator => Self::StrAsciiIterator, + BuiltinType::StrIterator => Self::StrIterator, + BuiltinType::BytesIterator => Self::BytesIterator, + BuiltinType::RangeIterator => Self::RangeIterator, + BuiltinType::DictKeyIterator => Self::DictKeyIterator, + BuiltinType::DictItemIterator => Self::DictItemIterator, + BuiltinType::DictValueIterator => Self::DictValueIterator, + BuiltinType::SetIterator => Self::SetIterator, + BuiltinType::ItertoolsCount => Self::ItertoolsCount, + BuiltinType::ItertoolsRepeat => Self::ItertoolsRepeat, + BuiltinType::DataclassField => Self::DataclassField, + BuiltinType::Deque => Self::Deque, + BuiltinType::DequeIterator => Self::DequeIterator, + BuiltinType::ItertoolsPairwise => Self::ItertoolsPairwise, + BuiltinType::ItertoolsCompress => Self::ItertoolsCompress, + BuiltinType::ItertoolsIslice => Self::ItertoolsIslice, + BuiltinType::ItertoolsChain => Self::ItertoolsChain, + BuiltinType::ItertoolsCycle => Self::ItertoolsCycle, + BuiltinType::DataclassParams => Self::DataclassParams, + BuiltinType::MissingType => Self::MissingType, + BuiltinType::ItertoolsTakeWhile => Self::ItertoolsTakeWhile, + BuiltinType::ItertoolsDropWhile => Self::ItertoolsDropWhile, + BuiltinType::ItertoolsFilterFalse => Self::ItertoolsFilterFalse, + BuiltinType::ItertoolsStarMap => Self::ItertoolsStarMap, + BuiltinType::Object => Self::Object, + BuiltinType::Time => Self::Time, + BuiltinType::Partial => Self::Partial, + BuiltinType::ItertoolsAccumulate => Self::ItertoolsAccumulate, + BuiltinType::ItertoolsBatched => Self::ItertoolsBatched, + BuiltinType::ItertoolsZipLongest => Self::ItertoolsZipLongest, + BuiltinType::GenericAlias => Self::GenericAlias, + BuiltinType::Union => Self::Union, + BuiltinType::ItertoolsCombinations => Self::ItertoolsCombinations, + BuiltinType::ItertoolsCombinationsWithReplacement => Self::ItertoolsCombinationsWithReplacement, + BuiltinType::ItertoolsPermutations => Self::ItertoolsPermutations, + BuiltinType::ItertoolsProduct => Self::ItertoolsProduct, + BuiltinType::ItertoolsGroupBy => Self::ItertoolsGroupBy, + BuiltinType::ItertoolsGrouper => Self::ItertoolsGrouper, + BuiltinType::ItertoolsTee => Self::ItertoolsTee, + BuiltinType::ItertoolsTeeDataObject => Self::ItertoolsTeeDataObject, + BuiltinType::Random => Self::Random, + BuiltinType::LruCacheWrapper => Self::LruCacheWrapper, + BuiltinType::HashlibHash => Self::HashlibHash, + BuiltinType::HashlibHashXof => Self::HashlibHashXof, + BuiltinType::Blake2b => Self::Blake2b, + BuiltinType::Blake2s => Self::Blake2s, + BuiltinType::CsvReader => Self::CsvReader, + BuiltinType::CsvWriter => Self::CsvWriter, + BuiltinType::CsvDictReader => Self::CsvDictReader, + BuiltinType::CsvDictWriter => Self::CsvDictWriter, + BuiltinType::CsvDialect => Self::CsvDialect, + BuiltinType::Decimal => Self::Decimal, + BuiltinType::DecimalContext => Self::DecimalContext, + BuiltinType::DecimalSignalDict => Self::DecimalSignalDict, + BuiltinType::DecimalContextManager => Self::DecimalContextManager, + BuiltinType::ForwardRef => Self::ForwardRef, + } + } +} + +impl TryFrom for BuiltinType { + type Error = &'static str; + + fn try_from(value: Type) -> Result { + Ok(match value { + Type::Ellipsis => Self::Ellipsis, + Type::NotImplementedType => Self::NotImplementedType, + Type::Type => Self::Type, + Type::NoneType => Self::NoneType, + Type::Bool => Self::Bool, + Type::Int => Self::Int, + Type::Float => Self::Float, + Type::Complex => Self::Complex, + Type::Range => Self::Range, + Type::Slice => Self::Slice, + Type::Date => Self::Date, + Type::DateTime => Self::DateTime, + Type::TimeDelta => Self::TimeDelta, + Type::TimeZone => Self::TimeZone, + Type::Str => Self::Str, + Type::Bytes => Self::Bytes, + Type::List => Self::List, + Type::Tuple => Self::Tuple, + Type::NamedTuple => Self::NamedTuple, + Type::Dict => Self::Dict, + Type::DefaultDict => Self::DefaultDict, + Type::Counter => Self::Counter, + Type::DictKeys => Self::DictKeys, + Type::DictItems => Self::DictItems, + Type::DictValues => Self::DictValues, + Type::Set => Self::Set, + Type::FrozenSet => Self::FrozenSet, + Type::HostClass => Self::HostClass, + Type::Exception(exc_type) => Self::Exception(exc_type), + Type::Function => Self::Function, + Type::BuiltinFunction => Self::BuiltinFunction, + Type::Cell => Self::Cell, + Type::Iterator => Self::Iterator, + Type::ListIterator => Self::ListIterator, + Type::CallableIterator => Self::CallableIterator, + Type::Coroutine => Self::Coroutine, + Type::Module => Self::Module, + Type::TextIOWrapper => Self::TextIOWrapper, + Type::BufferedReader => Self::BufferedReader, + Type::BufferedWriter => Self::BufferedWriter, + Type::BufferedRandom => Self::BufferedRandom, + Type::SpecialForm => Self::SpecialForm, + Type::Path => Self::Path, + Type::Property => Self::Property, + Type::RePattern => Self::RePattern, + Type::ReMatch => Self::ReMatch, + Type::DirEntry => Self::DirEntry, + Type::ScandirIterator => Self::ScandirIterator, + Type::WalkGenerator => Self::WalkGenerator, + Type::TupleIterator => Self::TupleIterator, + Type::StrAsciiIterator => Self::StrAsciiIterator, + Type::StrIterator => Self::StrIterator, + Type::BytesIterator => Self::BytesIterator, + Type::RangeIterator => Self::RangeIterator, + Type::DictKeyIterator => Self::DictKeyIterator, + Type::DictItemIterator => Self::DictItemIterator, + Type::DictValueIterator => Self::DictValueIterator, + Type::SetIterator => Self::SetIterator, + Type::ItertoolsCount => Self::ItertoolsCount, + Type::ItertoolsRepeat => Self::ItertoolsRepeat, + Type::DataclassField => Self::DataclassField, + Type::Deque => Self::Deque, + Type::DequeIterator => Self::DequeIterator, + Type::ItertoolsPairwise => Self::ItertoolsPairwise, + Type::ItertoolsCompress => Self::ItertoolsCompress, + Type::ItertoolsIslice => Self::ItertoolsIslice, + Type::ItertoolsChain => Self::ItertoolsChain, + Type::ItertoolsCycle => Self::ItertoolsCycle, + Type::DataclassParams => Self::DataclassParams, + Type::MissingType => Self::MissingType, + Type::ItertoolsTakeWhile => Self::ItertoolsTakeWhile, + Type::ItertoolsDropWhile => Self::ItertoolsDropWhile, + Type::ItertoolsFilterFalse => Self::ItertoolsFilterFalse, + Type::ItertoolsStarMap => Self::ItertoolsStarMap, + Type::Object => Self::Object, + Type::Time => Self::Time, + Type::Partial => Self::Partial, + Type::ItertoolsAccumulate => Self::ItertoolsAccumulate, + Type::ItertoolsBatched => Self::ItertoolsBatched, + Type::ItertoolsZipLongest => Self::ItertoolsZipLongest, + Type::GenericAlias => Self::GenericAlias, + Type::Union => Self::Union, + Type::ItertoolsCombinations => Self::ItertoolsCombinations, + Type::ItertoolsCombinationsWithReplacement => Self::ItertoolsCombinationsWithReplacement, + Type::ItertoolsPermutations => Self::ItertoolsPermutations, + Type::ItertoolsProduct => Self::ItertoolsProduct, + Type::ItertoolsGroupBy => Self::ItertoolsGroupBy, + Type::ItertoolsGrouper => Self::ItertoolsGrouper, + Type::ItertoolsTee => Self::ItertoolsTee, + Type::ItertoolsTeeDataObject => Self::ItertoolsTeeDataObject, + Type::Random => Self::Random, + Type::LruCacheWrapper => Self::LruCacheWrapper, + Type::HashlibHash => Self::HashlibHash, + Type::HashlibHashXof => Self::HashlibHashXof, + Type::Blake2b => Self::Blake2b, + Type::Blake2s => Self::Blake2s, + Type::CsvReader => Self::CsvReader, + Type::CsvWriter => Self::CsvWriter, + Type::CsvDictReader => Self::CsvDictReader, + Type::CsvDictWriter => Self::CsvDictWriter, + Type::CsvDialect => Self::CsvDialect, + Type::Decimal => Self::Decimal, + Type::DecimalContext => Self::DecimalContext, + Type::DecimalSignalDict => Self::DecimalSignalDict, + Type::DecimalContextManager => Self::DecimalContextManager, + Type::ForwardRef => Self::ForwardRef, + Type::Instance(_) => return Err("user-defined classes use heap type objects"), + }) + } +} + +impl fmt::Display for BuiltinType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Type::from(*self).fmt(f) + } +} + +#[cfg(test)] +mod builtin_type_tests { + use std::mem::size_of; + + use strum::VariantNames; + + use super::{BuiltinType, ExcType, Type}; + use crate::{builtins::Builtins, heap::HeapId, value::Value}; + + #[test] + fn builtin_type_names_match_runtime_types() { + let runtime_names: Vec<_> = Type::VARIANTS + .iter() + .copied() + .filter(|name| *name != "instance") + .collect(); + assert_eq!(BuiltinType::VARIANTS, runtime_names); + + for name in runtime_names.into_iter().filter(|name| *name != "exception") { + let builtin: BuiltinType = name.parse().unwrap(); + let runtime: Type = name.parse().unwrap(); + assert_eq!(Type::from(builtin), runtime, "{name}"); + + let builtin_name: &'static str = builtin.into(); + let runtime_name: &'static str = runtime.into(); + assert_eq!(builtin_name, runtime_name, "{name}"); + } + } + + #[test] + fn static_type_conversions_preserve_serialization() { + let types = Type::VARIANTS + .iter() + .filter(|name| !matches!(**name, "instance" | "exception")) + .map(|name| name.parse::().unwrap()); + let exceptions = ExcType::VARIANTS + .iter() + .map(|name| Type::Exception(name.parse().unwrap())); + assert_eq!(BuiltinType::VARIANTS.len() + 1, Type::VARIANTS.len()); + + for ty in types.chain(exceptions) { + let builtin = BuiltinType::try_from(ty).unwrap(); + assert_eq!(Type::from(builtin), ty); + assert_eq!(builtin.to_string(), ty.to_string()); + + let cbor = minicbor_serde::to_vec(ty).unwrap(); + assert_eq!(minicbor_serde::to_vec(builtin).unwrap(), cbor); + assert_eq!(minicbor_serde::from_slice::(&cbor).unwrap(), builtin); + + // id() encodes builtins through postcard, whose variant indices must also stay stable. + let postcard = postcard::to_allocvec(&ty).unwrap(); + assert_eq!(postcard::to_allocvec(&builtin).unwrap(), postcard); + assert_eq!(postcard::from_bytes::(&postcard).unwrap(), builtin); + } + } + + // Captured from Type before the split. Updating this fixture requires checking + // dump compatibility and id() stability, not just regenerating expected output. + #[test] + fn builtin_type_serialization_matches_legacy_format() { + let fixture = include_str!("../../tests/fixtures/builtin_type_serialization.txt"); + assert_eq!(fixture.lines().count() + 1, BuiltinType::VARIANTS.len()); + + for line in fixture.lines() { + let (name, index) = line.split_once(' ').unwrap(); + let cbor = minicbor_serde::to_vec(name).unwrap(); + let builtin: BuiltinType = minicbor_serde::from_slice(&cbor).unwrap(); + + assert_eq!(minicbor_serde::to_vec(builtin).unwrap(), cbor, "{name}"); + let postcard = vec![index.parse::().unwrap()]; + assert_eq!(postcard::to_allocvec(&builtin).unwrap(), postcard, "{name}"); + assert_eq!(postcard::from_bytes::(&postcard).unwrap(), builtin); + } + + // Exception carries a payload and follows the removed Instance slot. + let cbor = b"\xa1\x69Exception\x6aValueError"; + let builtin = BuiltinType::Exception(ExcType::ValueError); + assert_eq!(minicbor_serde::to_vec(builtin).unwrap(), cbor); + assert_eq!(minicbor_serde::from_slice::(cbor).unwrap(), builtin); + let postcard = [29, 17]; + assert_eq!(postcard::to_allocvec(&builtin).unwrap(), postcard); + assert_eq!(postcard::from_bytes::(&postcard).unwrap(), builtin); + } + + #[test] + fn instance_types_cannot_be_builtins() { + let instance = Type::Instance(HeapId::from_index(0)); + assert!(BuiltinType::try_from(instance).is_err()); + + let cbor = minicbor_serde::to_vec(instance).unwrap(); + assert!(minicbor_serde::from_slice::(&cbor).is_err()); + + let postcard = postcard::to_allocvec(&instance).unwrap(); + assert!(postcard::from_bytes::(&postcard).is_err()); + } + + #[test] + fn compact_builtin_layout() { + assert_eq!(size_of::(), 1); + assert_eq!(size_of::(), 2); + + #[cfg(target_pointer_width = "64")] + assert_eq!(size_of::(), 16); + } +} diff --git a/crates/bashkit-monty/src/types/bytes.rs b/crates/bashkit-monty/src/types/bytes.rs index 85b1b4a09..222aebdb1 100644 --- a/crates/bashkit-monty/src/types/bytes.rs +++ b/crates/bashkit-monty/src/types/bytes.rs @@ -68,7 +68,7 @@ use std::{cell::Cell, ffi::c_int, fmt::Write, ops, str}; /// - `translate(table[, delete])` - Character translation /// - `maketrans(frm, to)` - Create translation table (staticmethod) use memchr::memmem::{Finder, FinderRev}; -use monty_types::ResourceError; +use monty_types::{ResourceError, ResourceTracker}; pub use monty_types::{bytes_repr, bytes_repr_fmt}; use smallvec::smallvec; @@ -86,14 +86,14 @@ use crate::{ identity::Identity, intern::{BytesId, StaticStrings}, percent_format::{copy_bytes_template, percent_format_bytes}, - resource_checks::{check_repeat_size, check_replace_size}, + py_value::PyValue, + resource_checks::{check_repeat_size, check_replace_size, push_checked, repeated_len, try_vec_with_capacity}, types::{ List, - long_int::repeat_count, py_trait::PyObjectIdentity, - slice::{optional_sequence_bound, slice_collect_iterator}, + slice::{SearchRange, search_range, slice_collect_iterator}, }, - value::{EitherStr, Value, eq_bytes}, + value::{EitherStr, VALUE_SIZE, Value, eq_bytes}, }; // ============================================================================= @@ -176,17 +176,13 @@ impl Bytes { defer_drop!(source, vm); defer_drop!(encoding, vm); defer_drop!(errors, vm); - let source_str = match source { - Some(v) if v.is_str(vm.heap) => Some(v), - _ => None, - }; + let source_str = source.as_ref().and_then(|value| value.as_str(vm)); // CPython's `bytes_new` ordering: an encoding demands a str source, a // str source demands an encoding, and a lone `errors` is never valid. if let Some(encoding) = encoding { - let Some(v) = source_str else { + let Some(s) = source_str else { return Err(ExcType::type_error_encoding_without_string()); }; - let s = v.to_str(vm)?; let errors = errors.as_ref().map_or("strict", |e| e.as_str(vm)); let encoding = encoding.as_str(vm); let codec = Codec::find(encoding).ok_or_else(|| ExcType::lookup_error_unknown_encoding(encoding))?; @@ -259,14 +255,20 @@ pub(crate) fn concat_bytes(lhs: &[u8], rhs: &[u8], heap: &Heap) -> Result) -> RunResult> { - let Some(count) = repeat_count(count, vm)? else { - return Ok(None); - }; +/// +/// Raises CPython's `OverflowError` past `isize::MAX` bytes and `MemoryError` when the +/// allocator refuses, where `slice::repeat` would panic or abort with no memory limit set. +fn repeat_bytes(value: &[u8], count: usize, vm: &VM<'_>) -> RunResult> { + let total = repeated_len(value.len(), count, 1).map_err(|_| ExcType::repeated_bytes_too_long())?; check_repeat_size(value.len(), count, &vm.heap.tracker)?; - Ok(Some(Value::Ref( - vm.heap.allocate(HeapData::Bytes(value.repeat(count).into())), - ))) + let mut repeated = try_vec_with_capacity(total)?; + if total > 0 { + repeated.extend_from_slice(value); + while repeated.len() < total { + repeated.extend_from_within(..repeated.len().min(total - repeated.len())); + } + } + Ok(Some(Value::Ref(vm.heap.allocate(HeapData::Bytes(repeated.into()))))) } /// An allocation-free bytes view retaining its interned or heap identity. @@ -333,7 +335,10 @@ impl<'h> PyTrait<'h> for PyBytes<'h> { } fn py_mul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { - repeat_bytes(self.as_slice(vm), other, vm) + let Some(count) = other.py_value(vm).repeat_count(vm)? else { + return Ok(None); + }; + repeat_bytes(self.as_slice(vm), count, vm) } fn py_rmul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { @@ -458,14 +463,6 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Bytes> { bytes_add(self.get(vm.heap).as_slice(), other, vm) } - fn py_mul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { - repeat_bytes(self.get(vm.heap).as_slice(), other, vm) - } - - fn py_rmul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { - self.py_mul_impl(other, vm) - } - /// `bytes % args` is printf-style formatting, see `percent_format`. fn py_mod_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { let template = copy_bytes_template(self.get(vm.heap).as_slice(), &vm.heap.tracker)?; @@ -778,7 +775,11 @@ fn count_non_overlapping(haystack: &[u8], needle: &[u8], heap: &Heap) -> Result< /// Returns the number of non-overlapping occurrences of the subsequence. fn bytes_count<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { let len = bytes.get(vm.heap).len(); - let (sub, start, end) = parse_bytes_sub_args("bytes.count", len, args, vm)?; + let (sub, range) = parse_bytes_sub_args("bytes.count", len, args, vm)?; + let Some((start, end)) = range else { + // `start` past `end` counts nothing: `b'abc'.count(b'', 2, 1) == 0` + return Ok(Value::Int(0)); + }; let slice = &bytes.get(vm.heap)[start..end]; let count = if sub.is_empty() { @@ -797,7 +798,11 @@ fn bytes_count<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM /// Returns the lowest index where the subsequence is found, or -1 if not found. fn bytes_find<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { let len = bytes.get(vm.heap).len(); - let (sub, start, end) = parse_bytes_sub_args("bytes.find", len, args, vm)?; + let (sub, range) = parse_bytes_sub_args("bytes.find", len, args, vm)?; + let Some((start, end)) = range else { + // `start` past `end` finds nothing: `b'abc'.find(b'', 4) == -1` + return Ok(Value::Int(-1)); + }; let slice = &bytes.get(vm.heap)[start..end]; let result = if sub.is_empty() { @@ -819,7 +824,11 @@ fn bytes_find<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM< /// Like find(), but raises ValueError if the subsequence is not found. fn bytes_index<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { let len = bytes.get(vm.heap).len(); - let (sub, start, end) = parse_bytes_sub_args("bytes.index", len, args, vm)?; + let (sub, range) = parse_bytes_sub_args("bytes.index", len, args, vm)?; + let Some((start, end)) = range else { + // `start` past `end` finds nothing: `b'abc'.index(b'', 4)` raises `ValueError` + return Err(ExcType::value_error_subsequence_not_found()); + }; let slice = &bytes.get(vm.heap)[start..end]; let result = if sub.is_empty() { @@ -845,7 +854,11 @@ fn bytes_index<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM /// if any of the prefixes match. fn bytes_startswith<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { let len = bytes.get(vm.heap).len(); - let (prefix_arg, start, end) = parse_bytes_prefix_suffix_args("bytes.startswith", len, args, vm)?; + let (prefix_arg, range) = parse_bytes_prefix_suffix_args("bytes.startswith", len, args, vm)?; + let Some((start, end)) = range else { + // `start` past `end` matches nothing: `b'abc'.startswith(b'', 4) == False` + return Ok(Value::Bool(false)); + }; let slice = &bytes.get(vm.heap)[start..end]; let result = match prefix_arg { @@ -862,7 +875,11 @@ fn bytes_startswith<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &m /// if any of the suffixes match. fn bytes_endswith<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { let len = bytes.get(vm.heap).len(); - let (suffix_arg, start, end) = parse_bytes_prefix_suffix_args("bytes.endswith", len, args, vm)?; + let (suffix_arg, range) = parse_bytes_prefix_suffix_args("bytes.endswith", len, args, vm)?; + let Some((start, end)) = range else { + // `start` past `end` matches nothing: `b'abc'.endswith(b'', 4) == False` + return Ok(Value::Bool(false)); + }; let slice = &bytes.get(vm.heap)[start..end]; let result = match suffix_arg { @@ -885,40 +902,27 @@ enum PrefixSuffixArg { /// Parses arguments for bytes.startswith/endswith methods. /// -/// Returns (prefix/suffix_arg, start, end) where start and end are normalized indices. +/// Returns the prefix/suffix_arg and the `(start, end)` range to match in, or +/// `None` for a `start` past `end`, where nothing matches (see [`search_range`]). /// The prefix/suffix_arg can be a single bytes value or a tuple of bytes values. -/// Guarantees `start <= end` to prevent slice panics. fn parse_bytes_prefix_suffix_args( method: &str, len: usize, args: ArgValues, vm: &mut VM<'_>, -) -> RunResult<(PrefixSuffixArg, usize, usize)> { +) -> RunResult<(PrefixSuffixArg, SearchRange)> { let pos = args.into_pos_only(method, vm.heap)?; defer_drop!(pos, vm); - let (prefix, start, end) = match pos.as_slice() { - [prefix_value] => { - let prefix = extract_bytes_for_prefix_suffix(prefix_value, method, vm)?; - (prefix, 0, len) - } - [prefix_value, start_value] => { - let prefix = extract_bytes_for_prefix_suffix(prefix_value, method, vm)?; - let start = optional_sequence_bound(start_value, 0, len, vm)?; - (prefix, start, len) - } - [prefix_value, start_value, end_value] => { + match pos.as_slice() { + [prefix_value, bounds @ ..] if bounds.len() <= 2 => { let prefix = extract_bytes_for_prefix_suffix(prefix_value, method, vm)?; - let start = optional_sequence_bound(start_value, 0, len, vm)?; - let end = optional_sequence_bound(end_value, len, len, vm)?; - (prefix, start, end) + let range = search_range(bounds.first(), bounds.get(1), len, vm)?; + Ok((prefix, range)) } - [] => return Err(ExcType::type_error_at_least(method, 1, 0)), - _ => return Err(ExcType::type_error_at_most(method, 3, pos.len())), - }; - - // Ensure start <= end to prevent slice panics - Ok((prefix, start, end.max(start))) + [] => Err(ExcType::type_error_at_least(method, 1, 0)), + _ => Err(ExcType::type_error_at_most(method, 3, pos.len())), + } } /// Extracts bytes (or tuple of bytes) for startswith/endswith methods. @@ -929,38 +933,28 @@ fn extract_bytes_for_prefix_suffix(value: &Value, method: &str, vm: &VM<'_>) -> // Extract the method name (e.g., "startswith" from "bytes.startswith") let method_name = method.strip_prefix("bytes.").unwrap_or(method); - match value { - Value::InternBytes(id) => Ok(PrefixSuffixArg::Single(vm.interns.get_bytes(*id).to_vec())), - Value::InternString(_) => Err(ExcType::type_error(format!( + match value.py_value(vm) { + PyValue::Bytes(bytes) => Ok(PrefixSuffixArg::Single(bytes.as_slice(vm).to_vec())), + PyValue::Str(_) => Err(ExcType::type_error(format!( "{method_name} first arg must be bytes or a tuple of bytes, not str" ))), - Value::Ref(id) => match vm.heap.get(*id) { - HeapData::Bytes(b) => Ok(PrefixSuffixArg::Single(b.as_slice().to_vec())), - HeapData::Str(_) => Err(ExcType::type_error(format!( - "{method_name} first arg must be bytes or a tuple of bytes, not str" - ))), - HeapData::Tuple(tuple) => { - // Extract each element as bytes - let items = tuple.as_slice(); - let mut prefixes = Vec::with_capacity(items.len()); - for (i, item) in items.iter().enumerate() { - if let Ok(b) = extract_single_bytes_for_prefix_suffix(item, vm) { - prefixes.push(b); - } else { - let item_type = item.py_type_name(vm); - return Err(ExcType::type_error(format!( - "{method_name} first arg must be bytes or a tuple of bytes, \ - not tuple containing {item_type} at index {i}" - ))); - } + PyValue::Tuple(tuple) => { + // Extract each element as bytes + let items = tuple.get(vm.heap).as_slice(); + let mut prefixes = Vec::with_capacity(items.len()); + for (i, item) in items.iter().enumerate() { + if let Ok(b) = extract_single_bytes_for_prefix_suffix(item, vm) { + prefixes.push(b); + } else { + let item_type = item.py_type_name(vm); + return Err(ExcType::type_error(format!( + "{method_name} first arg must be bytes or a tuple of bytes, \ + not tuple containing {item_type} at index {i}" + ))); } - Ok(PrefixSuffixArg::Multiple(prefixes)) } - _ => Err(ExcType::type_error(format!( - "{method_name} first arg must be bytes or a tuple of bytes, not {}", - value.py_type_name(vm) - ))), - }, + Ok(PrefixSuffixArg::Multiple(prefixes)) + } _ => Err(ExcType::type_error(format!( "{method_name} first arg must be bytes or a tuple of bytes, not {}", value.py_type_name(vm) @@ -970,13 +964,9 @@ fn extract_bytes_for_prefix_suffix(value: &Value, method: &str, vm: &VM<'_>) -> /// Extracts a single bytes value for tuple element in startswith/endswith. fn extract_single_bytes_for_prefix_suffix(value: &Value, vm: &VM<'_>) -> RunResult> { - match value { - Value::InternBytes(id) => Ok(vm.interns.get_bytes(*id).to_vec()), - Value::InternString(_) => Err(ExcType::type_error("expected bytes, not str")), - Value::Ref(id) => match vm.heap.get(*id) { - HeapData::Bytes(b) => Ok(b.as_slice().to_vec()), - _ => Err(ExcType::type_error("expected bytes")), - }, + match value.py_value(vm) { + PyValue::Bytes(bytes) => Ok(bytes.as_slice(vm).to_vec()), + PyValue::Str(_) => Err(ExcType::type_error("expected bytes, not str")), _ => Err(ExcType::type_error("expected bytes")), } } @@ -988,7 +978,9 @@ fn extract_single_bytes_for_prefix_suffix(value: &Value, vm: &VM<'_>) -> RunResu fn extract_bytes_only<'a>(value: &Value, vm: &'a VM<'_>) -> RunResult<&'a [u8]> { match value { Value::InternBytes(id) => Ok(vm.interns.get_bytes(*id)), - Value::InternString(_) => Err(ExcType::type_error("a bytes-like object is required, not 'str'")), + Value::InternString(_) | Value::InlineString(_) => { + Err(ExcType::type_error("a bytes-like object is required, not 'str'")) + } Value::Ref(id) => match vm.heap.get(*id) { HeapData::Bytes(b) => Ok(b.as_slice()), HeapData::Str(_) => Err(ExcType::type_error("a bytes-like object is required, not 'str'")), @@ -1000,38 +992,29 @@ fn extract_bytes_only<'a>(value: &Value, vm: &'a VM<'_>) -> RunResult<&'a [u8]> /// Parses arguments for bytes.find/count/index methods. /// -/// Returns (sub_bytes, start, end) where start and end are normalized indices. -/// Guarantees `start <= end` to prevent slice panics. +/// Returns the subsequence and the `(start, end)` range to search, or `None` +/// for a `start` past `end`, where nothing is found (see [`search_range`]). fn parse_bytes_sub_args( method: &str, len: usize, args: ArgValues, vm: &mut VM<'_>, -) -> RunResult<(Vec, usize, usize)> { +) -> RunResult<(Vec, SearchRange)> { let pos = args.into_pos_only(method, vm.heap)?; defer_drop!(pos, vm); // The bounds convert before `sub` is inspected, as in CPython, whose parser // runs the index converters and leaves the buffer check to the function body. // A raising `__index__` bound then costs no copy; `pos` keeps `sub` alive. - let (sub_value, start, end) = match pos.as_slice() { - [sub_value] => (sub_value, 0, len), - [sub_value, start_value] => { - let start = optional_sequence_bound(start_value, 0, len, vm)?; - (sub_value, start, len) - } - [sub_value, start_value, end_value] => { - let start = optional_sequence_bound(start_value, 0, len, vm)?; - let end = optional_sequence_bound(end_value, len, len, vm)?; - (sub_value, start, end) + let (sub_value, range) = match pos.as_slice() { + [sub_value, bounds @ ..] if bounds.len() <= 2 => { + (sub_value, search_range(bounds.first(), bounds.get(1), len, vm)?) } [] => return Err(ExcType::type_error_at_least(method, 1, 0)), _ => return Err(ExcType::type_error_at_most(method, 3, pos.len())), }; let sub = extract_bytes_only(sub_value, vm)?.to_owned(); - - // Ensure start <= end to prevent slice panics (Python treats start > end as empty slice) - Ok((sub, start, end.max(start))) + Ok((sub, range)) } // ============================================================================= @@ -1218,7 +1201,11 @@ fn bytes_istitle(bytes: &[u8]) -> bool { /// Returns the highest index where the subsequence is found, or -1 if not found. fn bytes_rfind<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { let len = bytes.get(vm.heap).len(); - let (sub, start, end) = parse_bytes_sub_args("bytes.rfind", len, args, vm)?; + let (sub, range) = parse_bytes_sub_args("bytes.rfind", len, args, vm)?; + let Some((start, end)) = range else { + // `start` past `end` finds nothing: `b'abc'.rfind(b'', 4) == -1` + return Ok(Value::Int(-1)); + }; let slice = &bytes.get(vm.heap)[start..end]; let result = if sub.is_empty() { @@ -1240,7 +1227,11 @@ fn bytes_rfind<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM /// Like rfind(), but raises ValueError if the subsequence is not found. fn bytes_rindex<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { let len = bytes.get(vm.heap).len(); - let (sub, start, end) = parse_bytes_sub_args("bytes.rindex", len, args, vm)?; + let (sub, range) = parse_bytes_sub_args("bytes.rindex", len, args, vm)?; + let Some((start, end)) = range else { + // `start` past `end` finds nothing: `b'abc'.rindex(b'', 4)` raises `ValueError` + return Err(ExcType::value_error_subsequence_not_found()); + }; let slice = &bytes.get(vm.heap)[start..end]; let result = if sub.is_empty() { @@ -1396,6 +1387,9 @@ fn bytes_split<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM let BytesSplitArgs { sep, maxsplit } = BytesSplitArgs::from_args(args, vm)?; let (sep, maxsplit) = coerce_bytes_split_args(sep, maxsplit, vm)?; + // Guarded before the subject borrow, so a limit error mid-loop releases the pieces built so far. + let mut items_guard = DropGuard::new(Vec::new(), vm); + let (list_items, vm) = items_guard.as_parts_mut(); let bytes = bytes.get(vm.heap); let parts: Vec<&[u8]> = match &sep { Some(sep) => { @@ -1411,20 +1405,25 @@ fn bytes_split<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM } None => { if maxsplit < 0 { - bytes_split_whitespace(bytes) + bytes_split_whitespace(bytes, &vm.heap.tracker)? } else { let max = usize::try_from(maxsplit).unwrap_or(usize::MAX); - bytes_splitn_whitespace(bytes, max) + bytes_splitn_whitespace(bytes, max, &vm.heap.tracker)? } } }; - let mut list_items = Vec::with_capacity(parts.len()); + vm.heap + .tracker + .check_allocation(parts.len().saturating_mul(VALUE_SIZE))?; + // `with_capacity` allocates directly; `reserve` on the empty guarded `Vec` takes the grow path. + *list_items = Vec::with_capacity(parts.len()); for (i, part) in parts.into_iter().enumerate() { vm.heap.tracker.check_memory_time_every(i)?; list_items.push(allocate_bytes(part.to_vec(), vm.heap)); } + let (list_items, vm) = items_guard.into_parts(); let list = List::new(list_items); let heap_id = vm.heap.allocate(HeapData::List(list)); Ok(Value::Ref(heap_id)) @@ -1437,6 +1436,9 @@ fn bytes_rsplit<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut V let BytesRsplitArgs { sep, maxsplit } = BytesRsplitArgs::from_args(args, vm)?; let (sep, maxsplit) = coerce_bytes_split_args(sep, maxsplit, vm)?; + // Guarded before the subject borrow, so a limit error mid-loop releases the pieces built so far. + let mut items_guard = DropGuard::new(Vec::new(), vm); + let (list_items, vm) = items_guard.as_parts_mut(); let bytes = bytes.get(vm.heap); let parts: Vec<&[u8]> = match &sep { Some(sep) => { @@ -1444,7 +1446,8 @@ fn bytes_rsplit<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut V return Err(ExcType::value_error_empty_separator()); } if maxsplit < 0 { - bytes_split_by_seq(bytes, sep, vm.heap)? + // From the right even when unlimited: overlapping matches pair up differently. + bytes_rsplitn_by_seq(bytes, sep, usize::MAX, vm.heap)? } else { let max = usize::try_from(maxsplit).unwrap_or(usize::MAX); bytes_rsplitn_by_seq(bytes, sep, max + 1, vm.heap)? @@ -1452,20 +1455,25 @@ fn bytes_rsplit<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut V } None => { if maxsplit < 0 { - bytes_split_whitespace(bytes) + bytes_split_whitespace(bytes, &vm.heap.tracker)? } else { let max = usize::try_from(maxsplit).unwrap_or(usize::MAX); - bytes_rsplitn_whitespace(bytes, max) + bytes_rsplitn_whitespace(bytes, max, &vm.heap.tracker)? } } }; - let mut list_items = Vec::with_capacity(parts.len()); + vm.heap + .tracker + .check_allocation(parts.len().saturating_mul(VALUE_SIZE))?; + // `with_capacity` allocates directly; `reserve` on the empty guarded `Vec` takes the grow path. + *list_items = Vec::with_capacity(parts.len()); for (i, part) in parts.into_iter().enumerate() { vm.heap.tracker.check_memory_time_every(i)?; list_items.push(allocate_bytes(part.to_vec(), vm.heap)); } + let (list_items, vm) = items_guard.into_parts(); let list = List::new(list_items); let heap_id = vm.heap.allocate(HeapData::List(list)); Ok(Value::Ref(heap_id)) @@ -1520,10 +1528,10 @@ fn bytes_split_by_seq<'a>(bytes: &'a [u8], sep: &[u8], heap: &Heap) -> Result(bytes: &'a [u8], sep: &[u8], n: usize, heap: &Heap) - while count + 1 < n { if let Some(pos) = find_with(&finder, &bytes[start..], heap)? { - parts.push(&bytes[start..start + pos]); + push_checked(&mut parts, &bytes[start..start + pos], &heap.tracker)?; start = start + pos + sep.len(); count += 1; } else { break; } } - parts.push(&bytes[start..]); + push_checked(&mut parts, &bytes[start..], &heap.tracker)?; Ok(parts) } @@ -1577,28 +1585,28 @@ fn bytes_rsplitn_by_seq<'a>( while count + 1 < n { if let Some(pos) = rfind_with(&finder, &bytes[..end], heap)? { - parts.push(&bytes[pos + sep.len()..end]); + push_checked(&mut parts, &bytes[pos + sep.len()..end], &heap.tracker)?; end = pos; count += 1; } else { break; } } - parts.push(&bytes[..end]); + push_checked(&mut parts, &bytes[..end], &heap.tracker)?; parts.reverse(); Ok(parts) } /// Splits bytes by ASCII whitespace, filtering empty parts. -fn bytes_split_whitespace(bytes: &[u8]) -> Vec<&[u8]> { +fn bytes_split_whitespace<'a>(bytes: &'a [u8], tracker: &ResourceTracker) -> Result, ResourceError> { let mut parts = Vec::new(); let mut start = None; for (i, &b) in bytes.iter().enumerate() { if is_py_whitespace(b) { if let Some(s) = start { - parts.push(&bytes[s..i]); + push_checked(&mut parts, &bytes[s..i], tracker)?; start = None; } } else if start.is_none() { @@ -1607,14 +1615,18 @@ fn bytes_split_whitespace(bytes: &[u8]) -> Vec<&[u8]> { } if let Some(s) = start { - parts.push(&bytes[s..]); + push_checked(&mut parts, &bytes[s..], tracker)?; } - parts + Ok(parts) } /// Splits bytes by ASCII whitespace, returning at most maxsplit+1 parts. -fn bytes_splitn_whitespace(bytes: &[u8], maxsplit: usize) -> Vec<&[u8]> { +fn bytes_splitn_whitespace<'a>( + bytes: &'a [u8], + maxsplit: usize, + tracker: &ResourceTracker, +) -> Result, ResourceError> { let mut parts = Vec::new(); let mut start = None; let mut count = 0; @@ -1627,7 +1639,7 @@ fn bytes_splitn_whitespace(bytes: &[u8], maxsplit: usize) -> Vec<&[u8]> { if let Some(s) = start && count < maxsplit { - parts.push(&bytes[offset + s..offset + i]); + push_checked(&mut parts, &bytes[offset + s..offset + i], tracker)?; count += 1; start = None; } @@ -1637,14 +1649,18 @@ fn bytes_splitn_whitespace(bytes: &[u8], maxsplit: usize) -> Vec<&[u8]> { } if let Some(s) = start { - parts.push(&bytes[offset + s..]); + push_checked(&mut parts, &bytes[offset + s..], tracker)?; } - parts + Ok(parts) } /// Splits bytes by ASCII whitespace from the right, returning at most maxsplit+1 parts. -fn bytes_rsplitn_whitespace(bytes: &[u8], maxsplit: usize) -> Vec<&[u8]> { +fn bytes_rsplitn_whitespace<'a>( + bytes: &'a [u8], + maxsplit: usize, + tracker: &ResourceTracker, +) -> Result, ResourceError> { let mut parts = Vec::new(); let mut end = None; let mut count = 0; @@ -1657,7 +1673,7 @@ fn bytes_rsplitn_whitespace(bytes: &[u8], maxsplit: usize) -> Vec<&[u8]> { if let Some(e) = end && count < maxsplit { - parts.push(&trimmed[i + 1..e]); + push_checked(&mut parts, &trimmed[i + 1..e], tracker)?; count += 1; end = None; } @@ -1667,11 +1683,11 @@ fn bytes_rsplitn_whitespace(bytes: &[u8], maxsplit: usize) -> Vec<&[u8]> { } if let Some(e) = end { - parts.push(&trimmed[..e]); + push_checked(&mut parts, &trimmed[..e], tracker)?; } parts.reverse(); - parts + Ok(parts) } /// Implements Python's `bytes.splitlines([keepends])` method. @@ -2257,22 +2273,26 @@ fn parse_bytes_hex_args(args: ArgValues, vm: &mut VM<'_>) -> RunResult<(Option vm.interns.get_str(*id).as_bytes(), - Value::InternBytes(id) => vm.interns.get_bytes(*id), - Value::Ref(heap_id) => match vm.heap.get(*heap_id) { - HeapData::Str(s) => s.as_bytes(), - HeapData::Bytes(b) => b.as_slice(), - _ => return Err(ExcType::type_error("sep must be str or bytes")), + let sep_char = match sep_value.py_value(vm) { + PyValue::Str(sep) => match sep.as_str(vm).as_bytes() { + [b] if b.is_ascii() => *b as char, + _ => { + return Err( + SimpleException::new_msg(ExcType::ValueError, "sep must be a single ASCII character").into(), + ); + } + }, + PyValue::Bytes(sep) => match sep.as_slice(vm) { + [b] if b.is_ascii() => *b as char, + _ => { + return Err( + SimpleException::new_msg(ExcType::ValueError, "sep must be a single ASCII character").into(), + ); + } }, _ => return Err(ExcType::type_error("sep must be str or bytes")), }; - let sep_char = match sep_bytes { - [b] if b.is_ascii() => *b as char, - _ => return Err(SimpleException::new_msg(ExcType::ValueError, "sep must be a single ASCII character").into()), - }; - let bytes_per_sep = match bytes_per_sep { Value::None => 1, bps_value => { @@ -2319,14 +2339,11 @@ pub fn bytes_fromhex(args: ArgValues, vm: &mut VM<'_>) -> RunResult { let hex_value = args.get_one_arg("bytes.fromhex", vm.heap)?; defer_drop!(hex_value, vm); - let hex_str = match hex_value { - Value::InternString(id) => vm.interns.get_str(*id), - Value::Ref(heap_id) => { - if let HeapData::Str(s) = vm.heap.get(*heap_id) { - s.as_str() - } else { - return Err(ExcType::type_error("fromhex() argument must be str, not bytes")); - } + let hex_value_py = hex_value.py_value(vm); + let hex_str = match &hex_value_py { + PyValue::Str(value) => value.as_str(vm), + PyValue::Bytes(_) => { + return Err(ExcType::type_error("fromhex() argument must be str, not bytes")); } _ => { let t = hex_value.py_type_name(vm); diff --git a/crates/bashkit-monty/src/types/class.rs b/crates/bashkit-monty/src/types/class.rs index d688025ae..e5a61eccb 100644 --- a/crates/bashkit-monty/src/types/class.rs +++ b/crates/bashkit-monty/src/types/class.rs @@ -2,8 +2,9 @@ use std::fmt::Write; use monty_types::MontyUuid; -use super::{Dict, LazyHeapSet, PyTrait, Type, attribute_name_value}; +use super::{Dict, LazyHeapSet, PyTrait, Type}; use crate::{ + annotations, args::ArgValues, boundary_uuid::create_uuid, bytecode::{CallResult, VM}, @@ -153,8 +154,11 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Class> { } fn py_set_attr(&mut self, name: &EitherStr, value: Value, vm: &mut VM<'h>) -> RunResult<()> { + if name.as_str(vm.interns) == "__annotations__" { + return annotations::set_class_annotations(self.id(), value, vm); + } let mut value_guard = DropGuard::new(value, vm); - let name = attribute_name_value(name, value_guard.ctx()); + let name = name.as_value(value_guard.ctx().heap); let (value, vm) = value_guard.into_parts(); let old_value = self.set_attr(name, value, vm)?; old_value.drop_with(vm); @@ -186,6 +190,11 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Class> { let name = self.get(vm.heap).name.as_str(vm.interns).to_owned(); return Ok(Some(CallResult::Value(allocate_string(name, vm.heap)))); } + // `Foo.__annotations__` is computed from the class's `__annotate__` on + // first access (PEP 649), another metaclass descriptor in CPython. + if attr_str == "__annotations__" { + return annotations::class_annotations(self.id(), vm).map(Some); + } // Otherwise look up a member (method or class variable) in the namespace. match self.get(vm.heap).namespace.get_by_str(attr_str, vm.heap, vm.interns) { Some(value) => Ok(Some(CallResult::Value(value.clone_with_heap(vm.heap)))), diff --git a/crates/bashkit-monty/src/types/csv/dialect.rs b/crates/bashkit-monty/src/types/csv/dialect.rs index aaba0b4e0..afa69f9cf 100644 --- a/crates/bashkit-monty/src/types/csv/dialect.rs +++ b/crates/bashkit-monty/src/types/csv/dialect.rs @@ -148,8 +148,8 @@ impl Dialect { let (params, vm) = params_guard.as_parts_mut(); let base = match base { None => Base::Defaults, - Some(value) if value.is_str(vm.heap) => { - Base::Dialect(Self::by_name(value.to_str(vm)?).ok_or_else(ExcType::csv_unknown_dialect)?) + Some(value) if let Some(name) = value.as_str(vm) => { + Base::Dialect(Self::by_name(name).ok_or_else(ExcType::csv_unknown_dialect)?) } Some(Value::Ref(id)) if let HeapData::Csv(csv) = vm.heap.get(*id) @@ -338,21 +338,16 @@ fn set_char_or_none( /// The character of a one-character `str`, with CPython's two wordings for a wrong /// type and a wrong length. fn single_char(name: &str, value: &Value, expected: &str, vm: &VM<'_>) -> RunResult { - if value.is_str(vm.heap) { - let text = value.to_str(vm)?; - let mut chars = text.chars(); - match (chars.next(), chars.next()) { - (Some(c), None) => Ok(c), - _ => Err(ExcType::type_error(format!( - "\"{name}\" must be {expected}, not a string of length {}", - text.chars().count() - ))), - } - } else { - Err(ExcType::type_error(format!( - "\"{name}\" must be {expected}, not {}", - value.py_type_name(vm) - ))) + let text = value + .as_str(vm) + .ok_or_else(|| ExcType::type_error(format!("\"{name}\" must be {expected}, not {}", value.py_type_name(vm))))?; + let mut chars = text.chars(); + match (chars.next(), chars.next()) { + (Some(c), None) => Ok(c), + _ => Err(ExcType::type_error(format!( + "\"{name}\" must be {expected}, not a string of length {}", + text.chars().count() + ))), } } @@ -371,14 +366,10 @@ fn set_str(name: &str, value: Option, default: &str, vm: &mut VM<'_>) -> let Some(value) = value else { return Ok(default.to_owned()); }; - let result = if value.is_str(vm.heap) { - value.to_str(vm).map(str::to_owned) - } else { - Err(ExcType::type_error(format!( - "\"{name}\" must be a string, not {}", - value.py_type_name(vm) - ))) - }; + let result = value + .as_str(vm) + .map(str::to_owned) + .ok_or_else(|| ExcType::type_error(format!("\"{name}\" must be a string, not {}", value.py_type_name(vm)))); value.drop_with(vm); result } diff --git a/crates/bashkit-monty/src/types/csv/dict.rs b/crates/bashkit-monty/src/types/csv/dict.rs index 56ff18c52..77392576a 100644 --- a/crates/bashkit-monty/src/types/csv/dict.rs +++ b/crates/bashkit-monty/src/types/csv/dict.rs @@ -402,7 +402,7 @@ impl RowSpec { defer_drop!(fieldnames, vm); defer_drop!(restval, vm); defer_drop!(extrasaction, vm); - let raise_on_extra = extrasaction.is_str(vm.heap) && extrasaction.to_str(vm)? == "raise"; + let raise_on_extra = extrasaction.as_str(vm) == Some("raise"); if raise_on_extra && row_dict(rowdict, vm).is_none() { return Err(dict_method_missing(rowdict, raise_on_extra, vm)); } @@ -547,7 +547,7 @@ fn check_extra_keys<'h>(dict: &HeapRead<'h, Dict>, known: &Value, vm: &mut VM<'h if any_wrong { builder.push_str(", ")?; } - builder.push_str(repr.to_str(vm)?)?; + builder.push_str(repr.as_str(vm).expect("py_repr returns str"))?; wrong = builder.finish_raw()?; any_wrong = true; } diff --git a/crates/bashkit-monty/src/types/csv/reader.rs b/crates/bashkit-monty/src/types/csv/reader.rs index 6cdf7f7dd..4c5810592 100644 --- a/crates/bashkit-monty/src/types/csv/reader.rs +++ b/crates/bashkit-monty/src/types/csv/reader.rs @@ -123,7 +123,9 @@ pub(super) fn next_fields<'h>(obj: &HeapReadMut<'h, CsvObject>, vm: &mut VM<'h>) } // The parser only allocates, so the line is read in place rather than copied. let heap: &Heap = vm.heap; - let mut rest = line.to_str_heap(heap, vm.interns)?; + let mut rest = line + .as_str_heap(heap, vm.interns) + .expect("reader line type checked above"); while !rest.is_empty() { heap.tracker.check_time_every(polls)?; polls += 1; diff --git a/crates/bashkit-monty/src/types/csv/writer.rs b/crates/bashkit-monty/src/types/csv/writer.rs index 57157c966..3772b711e 100644 --- a/crates/bashkit-monty/src/types/csv/writer.rs +++ b/crates/bashkit-monty/src/types/csv/writer.rs @@ -23,6 +23,7 @@ use crate::{ types::{ CsvObject, PyTrait, Type, csv::dialect::{Dialect, Quoting}, + instance, iter::collect_owned_iterable, str::allocate_string, }, @@ -258,7 +259,7 @@ pub(crate) fn format_row( append_field_data( dialect, terminator_chars, - text.to_str(vm)?, + text.as_str(vm).expect("py_str returns str"), &mut quoted, &mut field_buffer, &vm.heap.tracker, @@ -380,9 +381,15 @@ fn append_field( Ok(written) } -/// `PyNumber_Check`: the numeric types a `QUOTE_NONNUMERIC` writer leaves unquoted. +/// `PyNumber_Check`: built-in numbers and instances with `__int__`, `__float__`, or `__index__`, without conversions. fn is_number(value: &Value, vm: &VM<'_>) -> bool { - matches!(value.py_type(vm), Type::Int | Type::Float | Type::Bool | Type::Complex) + match value.py_type(vm) { + Type::Int | Type::Float | Type::Bool | Type::Complex => true, + Type::Instance(class_id) => ["__int__", "__float__", "__index__"] + .iter() + .any(|dunder| instance::class_defines(class_id, dunder, vm)), + _ => false, + } } /// Whether `value` is an `open()` file, whose `write()` yields a host call. diff --git a/crates/bashkit-monty/src/types/date.rs b/crates/bashkit-monty/src/types/date.rs index 6356237a0..89c231205 100644 --- a/crates/bashkit-monty/src/types/date.rs +++ b/crates/bashkit-monty/src/types/date.rs @@ -66,7 +66,8 @@ pub(crate) fn from_ymd(year: i32, month: i32, day: i32) -> RunResult { /// `date`'s year-range error, raised both by construction and by the probe /// [`datetime.astimezone`](super::datetime) makes a day either side of a value. -pub(crate) fn year_out_of_range(year: i32) -> RunError { +pub(crate) fn year_out_of_range(year: impl Into) -> RunError { + let year = year.into(); SimpleException::new_msg(ExcType::ValueError, format!("year must be in 1..9999, not {year}")).into() } @@ -99,14 +100,19 @@ fn max_day_for_month(year: i32, month: i32) -> u32 { /// Creates a date from a proleptic Gregorian ordinal value. pub(crate) fn from_ordinal(ordinal: i32) -> RunResult { let Some(date) = NaiveDate::from_num_days_from_ce_opt(ordinal) else { - return Err(SimpleException::new_msg(ExcType::OverflowError, "date value out of range").into()); + return Err(date_value_out_of_range()); }; if !(1..=9999).contains(&date.year()) { - return Err(SimpleException::new_msg(ExcType::OverflowError, "date value out of range").into()); + return Err(date_value_out_of_range()); } Ok(Date(date)) } +/// CPython's `OverflowError` for arithmetic that leaves years 1 to 9999. +pub(crate) fn date_value_out_of_range() -> RunError { + ExcType::overflow_error("date value out of range") +} + /// Returns the proleptic Gregorian ordinal (`1 == 0001-01-01`) for a date. #[must_use] pub(crate) fn to_ordinal(date: Date) -> i32 { @@ -154,6 +160,22 @@ pub(crate) fn class_today(vm: &mut VM<'_>, args: ArgValues) -> RunResult, args: ArgValues) -> RunResult { + let value = args + .reject_kwargs("date.fromtimestamp", vm.heap)? + .get_one_arg("date.fromtimestamp", vm.heap)?; + defer_drop!(value, vm); + // `date` floors to whole seconds and uses `__index__`-style wording, where + // `datetime` rounds to microseconds and names both numeric types. + let utc = datetime::timestamp_to_utc(value, datetime::TimestampRounding::Floor, vm)? + .ok_or_else(|| ExcType::type_error_not_integer(&value.py_type_name(vm)))?; + let offset = vm.env.os_policy.timezone.at(utc).offset_seconds; + let local = datetime::wall_clock_at(utc, offset)?; + Ok(Value::Ref(vm.heap.allocate(HeapData::Date(Date(local.date()))))) +} + /// Classmethod `date.fromisoformat(date_string)`. /// /// Parses ISO 8601 date strings in the formats `YYYY-MM-DD` and `YYYYMMDD`, @@ -189,14 +211,10 @@ pub(crate) fn allocate_ymd(year: i32, month: i32, day: i32, heap: &Heap) -> Valu /// Extracts a string from a `Value` for use by classmethods. pub(crate) fn extract_str_arg(value: &Value, method_name: &str, heap: &Heap, interns: &Interns) -> RunResult { - match value { - Value::InternString(string_id) => Ok(interns.get_str(*string_id).to_owned()), - Value::Ref(heap_id) => match heap.get(*heap_id) { - HeapData::Str(s) => Ok(s.as_str().to_owned()), - _ => Err(ExcType::type_error(format!("{method_name}: argument must be str"))), - }, - _ => Err(ExcType::type_error(format!("{method_name}: argument must be str"))), - } + value + .as_str_heap(heap, interns) + .map(str::to_owned) + .ok_or_else(|| ExcType::type_error(format!("{method_name}: argument must be str"))) } impl HeapItem for Date { @@ -250,14 +268,14 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Date> { let Some(HeapReadOutput::TimeDelta(other)) = other.read_heap(vm) else { return Ok(None); }; - Ok(py_add(*self.get(vm.heap), *other.get(vm.heap), vm.heap)) + py_add(*self.get(vm.heap), *other.get(vm.heap), vm.heap).map(Some) } fn py_sub_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { match other.read_heap(vm) { Some(HeapReadOutput::Date(other)) => Ok(py_sub_date(*self.get(vm.heap), *other.get(vm.heap), vm.heap)), Some(HeapReadOutput::TimeDelta(other)) => { - Ok(py_sub_timedelta(*self.get(vm.heap), *other.get(vm.heap), vm.heap)) + py_sub_timedelta(*self.get(vm.heap), *other.get(vm.heap), vm.heap).map(Some) } _ => Ok(None), } @@ -308,6 +326,8 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Date> { date.0.weekday().number_from_monday(), )))) } + // A classmethod, so CPython also reaches it through an instance. + Some(StaticStrings::Fromtimestamp) => class_fromtimestamp(vm, args).map(CallResult::Value), _ => Err(ExcType::attribute_error_method(Type::Date, attr, args, vm)), } } @@ -331,21 +351,23 @@ pub(crate) fn py_sub_date(a: Date, b: Date, heap: &mut Heap) -> Option { } /// `date + timedelta` helper. -pub(crate) fn py_add(date: Date, delta: TimeDelta, heap: &mut Heap) -> Option { +pub(crate) fn py_add(date: Date, delta: TimeDelta, heap: &mut Heap) -> RunResult { let (days, _, _) = timedelta::components(&delta); - let new_ordinal = i64::from(to_ordinal(date)).checked_add(i64::from(days))?; - let new_ordinal = i32::try_from(new_ordinal).ok()?; - let value = from_ordinal(new_ordinal).ok()?; - Some(Value::Ref(heap.allocate(HeapData::Date(value)))) + let value = offset_days(date, days)?; + Ok(Value::Ref(heap.allocate(HeapData::Date(value)))) } /// `date - timedelta` helper. -pub(crate) fn py_sub_timedelta(date: Date, delta: TimeDelta, heap: &mut Heap) -> Option { +pub(crate) fn py_sub_timedelta(date: Date, delta: TimeDelta, heap: &mut Heap) -> RunResult { let (days, _, _) = timedelta::components(&delta); - let new_ordinal = i64::from(to_ordinal(date)).checked_sub(i64::from(days))?; - let new_ordinal = i32::try_from(new_ordinal).ok()?; - let value = from_ordinal(new_ordinal).ok()?; - Some(Value::Ref(heap.allocate(HeapData::Date(value)))) + let value = offset_days(date, -days)?; + Ok(Value::Ref(heap.allocate(HeapData::Date(value)))) +} + +/// The date `days` after `date`, or CPython's `OverflowError` outside years 1 to 9999. +fn offset_days(date: Date, days: i32) -> RunResult { + // A timedelta has at most 999999999 days, so this cannot overflow `i32` + from_ordinal(to_ordinal(date) + days) } /// Formats a [`Date`] with a `strftime` directive string, shared by the diff --git a/crates/bashkit-monty/src/types/datetime.rs b/crates/bashkit-monty/src/types/datetime.rs index adc3190bf..21f857e7f 100644 --- a/crates/bashkit-monty/src/types/datetime.rs +++ b/crates/bashkit-monty/src/types/datetime.rs @@ -25,6 +25,7 @@ use crate::{ hash::HashValue, heap::{Heap, HeapData, HeapId, HeapItem, HeapObjectRead, HeapReadOutput}, intern::{Interns, StaticStrings}, + py_value::PyValue, types::{ CmpOrder, LazyHeapSet, PyTrait, TimeDelta, TimeZone, Type, date::{self, StrftimeArgs}, @@ -320,6 +321,179 @@ pub(crate) fn class_now(vm: &mut VM<'_>, args: ArgValues) -> RunResult, args: ArgValues) -> RunResult { + let FromtimestampArgs { timestamp, tz } = FromtimestampArgs::from_args(args, vm)?; + defer_drop!(timestamp, vm); + defer_drop!(tz, vm); + let (tz, tz_ref) = tzinfo_from_value(tz, vm.heap, vm.interns)?; + let utc = timestamp_to_utc(timestamp, TimestampRounding::HalfEven, vm)? + .ok_or_else(|| timestamp_not_a_number(timestamp, vm))?; + let mut dt = if let Some(tz) = tz { + // CPython builds the UTC value first, so its year error comes first, and a + // shifted result that leaves the range is `fromutc()`'s overflow. + if !year_in_python_range(utc.year()) { + return Err(date::year_out_of_range(utc.year())); + } + DateTime { + naive: wall_clock_at(utc, tz.offset_seconds).map_err(|_| date_out_of_range())?, + offset_seconds: Some(tz.offset_seconds), + timezone_name: tz.name, + tzinfo_ref: None, + } + } else { + let offset = vm.env.os_policy.timezone.at(utc).offset_seconds; + let naive = wall_clock_at(utc, offset)?; + // CPython detects a DST fold by then converting the instant a day earlier, + // so the first representable day raises its year error; reproduce that. + let probe = utc + .checked_sub_signed(ChronoTimeDelta::days(1)) + .ok_or_else(|| date::year_out_of_range(utc.year()))?; + wall_clock_at(probe, offset)?; + DateTime { + naive, + offset_seconds: None, + timezone_name: None, + tzinfo_ref: None, + } + }; + attach_or_allocate_tzinfo_ref(&mut dt, tz_ref, vm.heap); + Ok(Value::Ref(vm.heap.allocate(HeapData::DateTime(dt)))) +} + +/// Argument shape for `datetime.fromtimestamp(timestamp, tz=None)`, a +/// `PyArg_ParseTupleAndKeywords` parser: `at_most_total` gives CPython's +/// `fromtimestamp() takes at most 2 arguments (3 given)` for a duplicated `tz`. +#[derive(FromArgs)] +#[from_args(name = "fromtimestamp", style = c_named, at_most_total)] +struct FromtimestampArgs { + timestamp: Value, + #[from_args(default = Value::None)] + tz: Value, +} + +/// How a float `fromtimestamp()` argument is cut to the result's precision: +/// `datetime` rounds half-even to microseconds, `date` floors to whole seconds. +#[derive(Clone, Copy)] +pub(crate) enum TimestampRounding { + HalfEven, + Floor, +} + +/// The UTC instant a `fromtimestamp()` argument denotes. Integers, floats and +/// anything with `__index__` are accepted, as CPython's `PyLong_AsLongLong` path +/// accepts them; `None` for anything else, so the caller can word the type error. +pub(crate) fn timestamp_to_utc( + value: &Value, + rounding: TimestampRounding, + vm: &mut VM<'_>, +) -> RunResult> { + let Some((seconds, microseconds)) = timestamp_parts(value, rounding, vm)? else { + return Ok(None); + }; + chrono::DateTime::from_timestamp(seconds, microseconds * 1_000) + .map(|instant| Some(instant.naive_utc())) + .ok_or_else(|| beyond_chrono_range(seconds)) +} + +/// The error for a timestamp past chrono's ±262143 years. CPython's `localtime()` still +/// holds the year while `year - 1900` fits a C `int`, so it raises the year error; +/// past that it raises `OSError`, which Monty words as the `time_t` overflow. +/// The zone offset is ignored: it can only move the year within hours of a new year. +#[cold] +fn beyond_chrono_range(seconds: i64) -> RunError { + let year = civil_year(seconds); + if i32::try_from(year - 1900).is_ok() { + date::year_out_of_range(year) + } else { + ExcType::timestamp_out_of_range() + } +} + +/// The proleptic Gregorian year of the instant `seconds` after the Unix epoch, for any +/// `i64` (Howard Hinnant's `civil_from_days`), where chrono stops at ±262143 years. +fn civil_year(seconds: i64) -> i64 { + let shifted = seconds.div_euclid(86_400) + 719_468; + let era = shifted.div_euclid(146_097); + let day_of_era = shifted - era * 146_097; + let year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + // Years run March to February here, so January and February belong to the next one. + let march_based_month = (5 * day_of_year + 2) / 153; + year_of_era + era * 400 + i64::from(march_based_month >= 10) +} + +/// Whole seconds and microseconds of a timestamp argument, as CPython's +/// `_PyTime_ObjectToTimeval` / `_PyTime_ObjectToTime_t` read it; shared with the +/// `time` module. `None` when it is not a number and has no `__index__`. +pub(crate) fn timestamp_parts( + value: &Value, + rounding: TimestampRounding, + vm: &mut VM<'_>, +) -> RunResult> { + match value.py_value(vm) { + PyValue::Bool(b) => Ok(Some((i64::from(b), 0))), + PyValue::Int(integer) => Ok(Some(( + integer.to_i64(vm).ok_or_else(ExcType::timestamp_out_of_range)?, + 0, + ))), + PyValue::Float(f) => split_float_timestamp(f, rounding).map(Some), + _ => match value.py_index_impl(vm)? { + Some(index) => { + defer_drop!(index, vm); + timestamp_parts(index, rounding, vm) + } + None => Ok(None), + }, + } +} + +/// Splits a float timestamp into whole seconds and microseconds in `0..1_000_000`, +/// following CPython's `_PyTime_DoubleToDenominator` (half-even) or its +/// `_PyTime_ROUND_FLOOR` conversion to whole seconds. +// Both casts are range-checked: `whole` fits `i64` and `fraction` is a rounded value in `0..1_000_000`. +#[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)] +fn split_float_timestamp(value: f64, rounding: TimestampRounding) -> RunResult<(i64, u32)> { + if value.is_nan() { + return Err(ExcType::invalid_nan()); + } + let (mut whole, mut fraction) = match rounding { + TimestampRounding::HalfEven => { + let whole = value.trunc(); + (whole, ((value - whole) * 1_000_000.0).round_ties_even()) + } + TimestampRounding::Floor => (value.floor(), 0.0), + }; + if fraction >= 1_000_000.0 { + fraction -= 1_000_000.0; + whole += 1.0; + } else if fraction < 0.0 { + fraction += 1_000_000.0; + whole -= 1.0; + } + // `time_t` is 64 bits on every supported platform; the comparison also rejects infinities. + if !(-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&whole) { + return Err(ExcType::timestamp_out_of_range()); + } + Ok((whole as i64, fraction as u32)) +} + +/// The wall clock at `offset_seconds` from the UTC instant `utc`, raising CPython's +/// `year must be in 1..9999` when the result leaves `datetime`'s range. +pub(crate) fn wall_clock_at(utc: NaiveDateTime, offset_seconds: i32) -> RunResult { + local_wall_clock(utc, offset_seconds).ok_or_else(|| { + // Computed from seconds, since the shifted instant may be past chrono's range. + date::year_out_of_range(civil_year(utc.and_utc().timestamp() + i64::from(offset_seconds))) + }) +} + +#[cold] +fn timestamp_not_a_number(value: &Value, vm: &VM<'_>) -> RunError { + ExcType::type_error(format!("argument must be int or float, not {}", value.py_type_name(vm))) +} + /// `datetime.astimezone(tz=None)`: the same instant in `tz`, or in the sandbox /// zone at that instant when `tz` is `None`. A naive value is read as sandbox-local /// wall time, as CPython reads it in the host's zone. @@ -882,40 +1056,30 @@ fn chrono_strptime_formats(fmt: &str) -> Vec { vec![chrono_fmt] } -/// `datetime + timedelta` -pub(crate) fn py_add(datetime: &DateTime, delta: &TimeDelta, heap: &mut Heap) -> Option { - let chrono_delta = timedelta::chrono_delta(delta); - - let next = if let Some(offset) = datetime.offset_seconds { - let utc = to_utc_naive(datetime)?; - let next_utc = utc.checked_add_signed(chrono_delta)?; - from_utc_naive_with_timezone_parts(next_utc, offset, datetime.timezone_name.clone()) - } else { - let next_local = datetime.naive.checked_add_signed(chrono_delta)?; - from_local_naive(next_local) - }; - - let mut next = next?; - attach_or_allocate_tzinfo_ref(&mut next, datetime.tzinfo_ref, heap); - Some(Value::Ref(heap.allocate(HeapData::DateTime(next)))) +/// `datetime + timedelta`, raising CPython's `OverflowError` outside years 1 to 9999. +pub(crate) fn py_add(datetime: &DateTime, delta: &TimeDelta, heap: &mut Heap) -> RunResult { + offset_datetime(datetime, timedelta::chrono_delta(delta), heap) } -/// `datetime - timedelta` -pub(crate) fn py_sub_timedelta(datetime: &DateTime, delta: &TimeDelta, heap: &mut Heap) -> Option { - let chrono_delta = timedelta::chrono_delta(delta); +/// `datetime - timedelta`, raising CPython's `OverflowError` outside years 1 to 9999. +pub(crate) fn py_sub_timedelta(datetime: &DateTime, delta: &TimeDelta, heap: &mut Heap) -> RunResult { + // Negate the Chrono duration, not the Python `timedelta`, which would overflow for `timedelta.max` + offset_datetime(datetime, -timedelta::chrono_delta(delta), heap) +} +/// The datetime `delta` after `datetime`, or CPython's `OverflowError` outside years 1 to 9999. +fn offset_datetime(datetime: &DateTime, delta: ChronoTimeDelta, heap: &mut Heap) -> RunResult { let next = if let Some(offset) = datetime.offset_seconds { - let utc = to_utc_naive(datetime)?; - let next_utc = utc.checked_sub_signed(chrono_delta)?; - from_utc_naive_with_timezone_parts(next_utc, offset, datetime.timezone_name.clone()) + to_utc_naive(datetime) + .and_then(|utc| utc.checked_add_signed(delta)) + .and_then(|next_utc| from_utc_naive_with_timezone_parts(next_utc, offset, datetime.timezone_name.clone())) } else { - let next_local = datetime.naive.checked_sub_signed(chrono_delta)?; - from_local_naive(next_local) + datetime.naive.checked_add_signed(delta).and_then(from_local_naive) }; - let mut next = next?; + let mut next = next.ok_or_else(date::date_value_out_of_range)?; attach_or_allocate_tzinfo_ref(&mut next, datetime.tzinfo_ref, heap); - Some(Value::Ref(heap.allocate(HeapData::DateTime(next)))) + Ok(Value::Ref(heap.allocate(HeapData::DateTime(next)))) } /// `datetime - datetime` returns a timedelta with the difference. @@ -1130,9 +1294,9 @@ struct IsoformatArgs { /// with the argument's length rather than its type. fn isoformat_separator(sep: Option<&Value>, vm: &VM<'_>) -> RunResult { let Some(sep) = sep else { return Ok('T') }; - // `to_str_heap`'s own message is the generic `expected string, not X`, so + // `try_to_str_heap`'s own message is the generic `expected string, not X`, so // only its success is used and the rejection is reworded here. - match sep.to_str_heap(vm.heap, vm.interns).ok() { + match sep.try_to_str_heap(vm.heap, vm.interns).ok() { Some(s) if s.chars().count() == 1 => Ok(s.chars().next().expect("just counted one char")), Some(s) => Err(ExcType::type_error_bad_arg_pos( "isoformat", @@ -1299,7 +1463,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, DateTime> { }; let value = self.get(vm.heap).clone(); let other = *other.get(vm.heap); - Ok(py_add(&value, &other, vm.heap)) + py_add(&value, &other, vm.heap).map(Some) } fn py_sub_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { @@ -1312,7 +1476,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, DateTime> { Some(HeapReadOutput::TimeDelta(other)) => { let value = self.get(vm.heap).clone(); let other = *other.get(vm.heap); - Ok(py_sub_timedelta(&value, &other, vm.heap)) + py_sub_timedelta(&value, &other, vm.heap).map(Some) } _ => Ok(None), } @@ -1389,6 +1553,8 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, DateTime> { Ok(CallResult::Value(Value::Float(ts))) } Some(StaticStrings::Astimezone) => astimezone(&dt, vm, args), + // A classmethod, so CPython also reaches it through an instance. + Some(StaticStrings::Fromtimestamp) => class_fromtimestamp(vm, args).map(CallResult::Value), Some(StaticStrings::Utcoffset) => { args.check_zero_args("datetime.utcoffset", vm.heap)?; Ok(CallResult::Value(timezone::utcoffset_value(dt.offset_seconds, vm.heap))) diff --git a/crates/bashkit-monty/src/types/decimal/py.rs b/crates/bashkit-monty/src/types/decimal/py.rs index 4caff4252..d86ef6472 100644 --- a/crates/bashkit-monty/src/types/decimal/py.rs +++ b/crates/bashkit-monty/src/types/decimal/py.rs @@ -33,7 +33,7 @@ use crate::{ intern::StaticStrings, py_value::PyValue, types::{ - CmpOrder, Complex, LazyHeapSet, LongInt, NamedTuple, PyTrait, Type, allocate_string, + BuiltinType, CmpOrder, Complex, LazyHeapSet, LongInt, NamedTuple, PyTrait, Type, allocate_string, str::allocate_string_no_interning, tuple::allocate_tuple, }, value::{EitherStr, Value}, @@ -858,7 +858,10 @@ impl<'h> HeapObjectRead<'h, Decimal> { DecimalMethod::DunderReduce => { let text = allocate_string(d.to_sci_string(false, true), vm.heap); let args = allocate_tuple(smallvec![text], vm.heap); - allocate_tuple(smallvec![Value::Builtin(Builtins::Type(Type::Decimal)), args], vm.heap) + allocate_tuple( + smallvec![Value::Builtin(Builtins::Type(BuiltinType::Decimal)), args], + vm.heap, + ) } DecimalMethod::DunderComplex => { let real = d.to_f64()?; diff --git a/crates/bashkit-monty/src/types/deque.rs b/crates/bashkit-monty/src/types/deque.rs index 03404cb00..4d36caf01 100644 --- a/crates/bashkit-monty/src/types/deque.rs +++ b/crates/bashkit-monty/src/types/deque.rs @@ -13,11 +13,12 @@ use crate::{ intern::StaticStrings, modules::copy::{Memo, PyDeepCopy, deep_copy}, py_value::PyValue, - resource_checks::{check_estimated_size, check_repeat_size, check_value_buffer_growth}, + resource_checks::{ + check_estimated_size, check_repeat_size, check_value_buffer_growth, repeated_len, try_vec_with_capacity, + }, types::{ LazyHeapSet, Type, list::repr_items_fmt, - long_int::repeat_count, slice::{normalize_sequence_index, value_to_i64_bound}, }, value::{EitherStr, VALUE_SIZE, Value}, @@ -560,8 +561,11 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Deque> { return Ok(None); }; let maxlen = self.get(vm.heap).maxlen(); - let mut items = self.clone_all_items(vm)?; - items.extend(other.clone_all_items(vm)?); + // The guard releases our clones if cloning `other` hits the memory limit. + let mut items = DropGuard::new(self.clone_all_items(vm)?, vm); + let (left, vm) = items.as_parts_mut(); + left.extend(other.clone_all_items(vm)?); + let (items, vm) = items.into_parts(); let (deque, evicted) = Deque::new(items, maxlen); evicted.drop_with(vm.heap); let id = vm.heap.allocate(HeapData::Deque(deque)); @@ -583,7 +587,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Deque> { /// `deque * int` — repetition that keeps the deque's `maxlen`, so a bounded /// deque builds only its surviving suffix rather than the full product. fn py_mul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { - let Some(count) = repeat_count(other, vm)? else { + let Some(count) = other.py_value(vm).repeat_count(vm)? else { return Ok(None); }; let maxlen = self.get(vm.heap).maxlen(); @@ -597,7 +601,44 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Deque> { self.get(vm.heap).iter().map(|v| v.clone_with_heap(vm.heap)).collect() }; let result = repeat_deque(source, maxlen, count, vm)?; - Ok(Some(result)) + Ok(Some(Value::Ref(vm.heap.allocate(HeapData::Deque(result))))) + } + + /// Repeats for integer or `__index__` counts, retaining identity and respecting `maxlen`. + fn py_imul_impl(&mut self, other: &Value, vm: &mut VM<'h>) -> RunResult { + let Some(count) = other.py_value(vm).repeat_count(vm)? else { + return Ok(false); + }; + + // These no-op repetitions must not invalidate iterators already traversing this deque. + if count == 1 || self.get(vm.heap).items.is_empty() { + return Ok(true); + } + + // `__index__` may mutate the deque; capture its contents and bound afterward. + let maxlen = self.get(vm.heap).maxlen; + let len = self.get(vm.heap).items.len(); + vm.heap + .tracker + .check_allocation(if count == 0 { 0 } else { len.saturating_mul(VALUE_SIZE) })?; + let source = if count == 0 { + Vec::new() + } else { + self.get(vm.heap) + .iter() + .map(|item| item.clone_with_heap(vm.heap)) + .collect() + }; + + // Build first so allocation/time failures preserve the original contents. + let mut result = repeat_deque(source, maxlen, count, vm)?; + // Advance the old mutation counter so iterators detect replacement at unchanged length. + result.state = self.get(vm.heap).state.wrapping_add(1); + let old = mem::replace(self.get_mut(vm.heap), result); + for item in old.items { + item.drop_with(vm); + } + Ok(true) } fn py_rmul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { @@ -1096,7 +1137,7 @@ fn deque_push<'h>(deque: &HeapReadMut<'h, Deque>, item: Value, end: ExtendEnd, v /// count, maxlen)` starts at `(len - L % len) % len`. An unbounded deque has no /// shortcut and materializes the full product (may hit resource limits, like /// CPython's `MemoryError`). -fn repeat_deque(source: Vec, maxlen: Option, count: usize, vm: &mut VM<'_>) -> RunResult { +fn repeat_deque(source: Vec, maxlen: Option, count: usize, vm: &mut VM<'_>) -> RunResult { let len = source.len(); // `source` is an owned copy of the deque's items; release it on every exit. defer_drop!(source, vm); @@ -1120,8 +1161,9 @@ fn repeat_deque(source: Vec, maxlen: Option, count: usize, vm: &mu } result.into_inner() } else { + let total = repeated_len(len, count, mem::size_of::())?; check_repeat_size(len.saturating_mul(mem::size_of::()), count, &vm.heap.tracker)?; - let mut result = DropGuard::new(Vec::with_capacity(len * count), vm); + let mut result = DropGuard::new(try_vec_with_capacity(total)?, vm); for rep in 0..count { let (items, vm) = result.as_parts_mut(); items.extend(source.iter().map(|v| v.clone_with_heap(vm.heap))); @@ -1133,7 +1175,7 @@ fn repeat_deque(source: Vec, maxlen: Option, count: usize, vm: &mu // no refcounts need releasing — `debug_assert` guards that invariant. let (new_deque, evicted) = Deque::new(result, maxlen); debug_assert!(evicted.is_empty(), "repeat_deque built more than maxlen items"); - Ok(Value::Ref(vm.heap.allocate(HeapData::Deque(new_deque)))) + Ok(new_deque) } impl<'h> PyDeepCopy<'h> for HeapRead<'h, Deque> { diff --git a/crates/bashkit-monty/src/types/dict.rs b/crates/bashkit-monty/src/types/dict.rs index 246364036..35928ef01 100644 --- a/crates/bashkit-monty/src/types/dict.rs +++ b/crates/bashkit-monty/src/types/dict.rs @@ -8,7 +8,9 @@ use std::{ use serde::ser::SerializeStruct; use smallvec::smallvec; -use super::{DictItemsView, DictKeysView, DictValuesView, LazyHeapSet, PyTrait, allocate_tuple, list::repr_check_time}; +use super::{ + DictItemsView, DictKeysView, DictValuesView, LazyHeapSet, PyTrait, allocate_tuple, list::repr_should_truncate, +}; use crate::{ args::{ArgValues, FromArgs, KwargsValues}, bytecode::{CallResult, ContainsVM, RecursionToken, VM}, @@ -375,12 +377,12 @@ impl Dict { json_key_equals_str(&entry.key, key_str, vm.heap, vm.interns) }); - let entry = DictEntry { key, value, hash }; if let Some(slot) = found { - let old_entry = self.table.replace(slot, entry); - old_entry.key.drop_with(vm); - Ok(Some(old_entry.value)) + let old_value = mem::replace(&mut self.table.entry_mut(slot).value, value); + key.drop_with(vm); + Ok(Some(old_value)) } else { + let entry = DictEntry { key, value, hash }; if let Err(err) = self.table.check_growth(&vm.heap.tracker) { entry.drop_with(vm); return Err(err.into()); @@ -396,14 +398,7 @@ impl Dict { /// JSON object parsing only inserts string keys, but the helper remains /// defensive and returns `None` for any non-string value. fn json_key_string_slice<'a>(key: &'a Value, heap: &'a Heap, interns: &'a Interns) -> Option<&'a str> { - match key { - Value::InternString(id) => Some(interns.get_str(*id)), - Value::Ref(id) => match heap.get(*id) { - HeapData::Str(string) => Some(string.as_str()), - _ => None, - }, - _ => None, - } + key.as_str_heap(heap, interns) } /// Returns whether `key` is a string equal to `expected`. @@ -411,14 +406,7 @@ fn json_key_string_slice<'a>(key: &'a Value, heap: &'a Heap, interns: &'a Intern /// This bypasses Python's full equality machinery because JSON object keys are /// always strings, so content comparison is sufficient and much cheaper. fn json_key_equals_str(key: &Value, expected: &str, heap: &Heap, interns: &Interns) -> bool { - match key { - Value::InternString(id) => interns.get_str(*id) == expected, - Value::Ref(id) => match heap.get(*id) { - HeapData::Str(string) => string.as_str() == expected, - _ => false, - }, - _ => false, - } + key.as_str_heap(heap, interns) == Some(expected) } impl<'h> HeapRead<'h, Dict> { @@ -575,8 +563,8 @@ impl Dict { /// are NOT incremented here - the caller is responsible for ensuring the refcounts /// were already incremented (e.g., via `clone_with_heap` or `evaluate_use`). /// - /// If the key already exists, replaces the old value and returns it (caller now - /// owns the old value and is responsible for its refcount). + /// If the key already exists, keeps the stored key, replaces the old value and + /// returns it (caller now owns the old value and is responsible for its refcount). /// Returns Err if key is unhashable or the insertion exceeds the memory limit; /// either way `key` and `value` are released, so the caller must not drop them. pub fn set(&mut self, key: Value, value: Value, vm: &mut VM<'_>) -> RunResult> { @@ -597,8 +585,8 @@ impl<'h> HeapReadMut<'h, Dict> { /// are NOT incremented here - the caller is responsible for ensuring the refcounts /// were already incremented (e.g., via `clone_with_heap` or `evaluate_use`). /// - /// If the key already exists, replaces the old value and returns it (caller now - /// owns the old value and is responsible for its refcount). + /// If the key already exists, keeps the stored key, replaces the old value and + /// returns it (caller now owns the old value and is responsible for its refcount). /// Returns Err if key is unhashable or the insertion exceeds the memory limit; /// either way `key` and `value` are released, so the caller must not drop them. pub fn set(&self, key: Value, value: Value, vm: &mut VM<'h>) -> RunResult> { @@ -662,16 +650,18 @@ impl<'h> HeapReadMut<'h, Dict> { } }; - let entry = DictEntry { key, value, hash }; if let Some(slot) = found { - // Key exists, replace in place to preserve insertion order - let old_entry = self.get_mut(vm.heap).table.replace(slot, entry); + // Key exists: as in CPython, keep the stored key and its position and + // rebind only the value, so `d = {1: 'a'}; d[True] = 'b'` gives `{1: 'b'}` + let entry = self.get_mut(vm.heap).table.entry_mut(slot); + let old_value = mem::replace(&mut entry.value, value); - // Decrement refcount for old key (we're discarding it) - old_entry.key.drop_with(vm); + // Decrement refcount for the new key (the stored key is kept) + key.drop_with(vm); // Transfer ownership of the old value to caller (no clone needed) - Ok(Some(old_entry.value)) + Ok(Some(old_value)) } else { + let entry = DictEntry { key, value, hash }; if growth == GrowthCheck::Preflight && let Err(err) = self.get(vm.heap).table.check_growth(&vm.heap.tracker) { @@ -810,6 +800,7 @@ pub(crate) fn probe_native_eq(candidate: &Value, key: &Value, vm: &VM<'_>) -> Op Value::Float(f) => eq_f64(*f, key, vm), Value::InternLongInt(id) => eq_bigint(vm.interns.get_long_int(*id), key, vm), Value::InternString(id) => eq_str(vm.interns.get_str(*id), key, vm), + Value::InlineString(text) => eq_str(text.as_str(), key, vm), Value::InternBytes(id) => eq_bytes(vm.interns.get_bytes(*id), key, vm), Value::Ref(id) => match vm.heap.get(*id) { HeapData::Str(s) => eq_str(s.as_str(), key, vm), @@ -1167,8 +1158,7 @@ impl<'h> HeapRead<'h, Dict> { defer_drop!(pair, vm); let (key, value) = pair; if printed > 0 { - // bashkit fork: `?` so a time hit errors instead of truncating (see `repr_check_time`). - if repr_check_time(printed, vm)? { + if repr_should_truncate(printed, vm)? { f.write_str(", ...[timeout]")?; break; } @@ -1204,12 +1194,19 @@ impl<'h> HeapRead<'h, Dict> { .tracker .check_allocation(pairs.len().saturating_mul(VALUE_SIZE + mem::size_of::()))?; let counts = pairs.iter().map(|(_, value)| value.clone_with_heap(vm.heap)).collect(); - let order = counter_order(counts, vm)?; + // CPython's `Counter.__repr__` falls back to insertion order when the counts + // cannot be ordered: it catches the `TypeError` from `most_common()`. + let order = match counter_order(counts, vm) { + Ok(order) => order, + Err(RunError::Exc(raise)) if raise.exc.exc_type().is_subclass_of(ExcType::TypeError) => { + (0..pairs.len()).collect() + } + Err(err) => return Err(err), + }; f.write_char('{')?; for (n, &i) in order.iter().enumerate() { if n > 0 { - // bashkit fork: `?` so a time hit errors instead of truncating (see `repr_check_time`). - if repr_check_time(n, vm)? { + if repr_should_truncate(n, vm)? { f.write_str(", ...[timeout]")?; break; } @@ -1739,14 +1736,8 @@ fn dict_or<'h>(left: &HeapRead<'h, Dict>, right: &Value, vm: &mut VM<'h>) -> Run let Some(HeapReadOutput::Dict(right_dict)) = right.read_heap(vm) else { return Ok(None); }; - // `from_pairs` builds a fresh dict of exactly these pairs while the snapshot - // is still live, so charge both: copying a near-limit dict must raise - // `MemoryError` rather than jump past the allocator's hard ceiling. The - // growth term is exact here only because the destination starts empty. let left_len = left.get(vm.heap).len(); - vm.heap.tracker.check_allocation( - left_len.saturating_mul(2 * VALUE_SIZE + mem::size_of::() + mem::size_of::()), - )?; + check_pairs_into_fresh_dict(left_len, vm)?; let pairs = left.clone_all_pairs(vm)?; let merged = Dict::from_pairs(pairs, vm)?; let mut merged_guard = DropGuard::new(merged, vm); @@ -1849,6 +1840,17 @@ fn check_pair_snapshot(len: usize, vm: &VM<'_>) -> RunResult<()> { Ok(vm.heap.tracker.check_allocation(len.saturating_mul(2 * VALUE_SIZE))?) } +/// Preflights a snapshot of `len` pairs and the fresh dict `from_pairs` builds +/// from it while the snapshot is still live, so copying a near-limit mapping +/// raises `MemoryError` rather than jumping past the allocator's hard ceiling. +/// The growth term is exact only because the destination starts empty. +pub(crate) fn check_pairs_into_fresh_dict(len: usize, vm: &VM<'_>) -> RunResult<()> { + Ok(vm + .heap + .tracker + .check_allocation(len.saturating_mul(2 * VALUE_SIZE + mem::size_of::() + mem::size_of::()))?) +} + /// Merges key-value pairs from an iterable of 2-item iterables. /// /// Each item from `iterable` is treated as `(key, value)`; see diff --git a/crates/bashkit-monty/src/types/file.rs b/crates/bashkit-monty/src/types/file.rs index 262eb997d..30c76fd2d 100644 --- a/crates/bashkit-monty/src/types/file.rs +++ b/crates/bashkit-monty/src/types/file.rs @@ -86,7 +86,7 @@ use monty_types::{MontyPath, OsFunctionCall, PathBytesDataArgs, PathStringDataAr use super::{ LazyHeapSet, List, PyTrait, Type, bytes::{Bytes, bytes_repr_fmt}, - str::{allocate_string, allocate_string_no_interning}, + str::{allocate_string, allocate_string_on_heap}, }; use crate::{ args::ArgValues, @@ -96,6 +96,7 @@ use crate::{ heap::{DropGuard, DropWithContext, Heap, HeapData, HeapId, HeapItem, HeapObjectRead, HeapReadMut, HeapReadOutput}, intern::StaticStrings, os_dispatch::PostConversionEffect, + py_value::PyValue, types::str::StringRepr, value::{EitherStr, Value}, virtual_path::posix_join, @@ -1092,10 +1093,8 @@ pub(crate) fn apply_file_next( } } -/// Installs a host `ReadText` / `ReadBytes` result as `file`'s buffer and -/// builds the position cache. Interned results are promoted to heap entries -/// and universal-newline text is translated here, once. A buffer already -/// present (a snapshot/restore race) is kept and the new content dropped. +/// Installs a host read result as a heap-backed buffer and builds the position cache. +/// Translates universal newlines once. If a buffer is already present, keeps it and drops the result. fn install_buffer<'h>(file: &HeapReadMut<'h, OpenFile>, result: Value, vm: &mut VM<'h>) -> RunResult<()> { let mut result_guard = DropGuard::new(result, vm); let (result, vm) = result_guard.as_parts_mut(); @@ -1105,14 +1104,14 @@ fn install_buffer<'h>(file: &HeapReadMut<'h, OpenFile>, result: Value, vm: &mut }; let replacement = match &*result { - Value::InternString(string_id) => { - let text = vm.interns.get_str(*string_id); + Value::InternString(_) | Value::InlineString(_) => { + let text = result.as_str(vm).expect("string result checked above"); let text = if translate { translate_newlines(text) } else { text.to_owned() }; - Some(allocate_string_no_interning(text, vm.heap)) + Some(allocate_string_on_heap(text, vm.heap)) } Value::InternBytes(bytes_id) => { let bytes = vm.interns.get_bytes(*bytes_id).to_vec(); @@ -1120,7 +1119,7 @@ fn install_buffer<'h>(file: &HeapReadMut<'h, OpenFile>, result: Value, vm: &mut } Value::Ref(id) => match vm.heap.get(*id) { HeapData::Str(text) if translate && text.as_str().contains('\r') => { - Some(allocate_string_no_interning(translate_newlines(text.as_str()), vm.heap)) + Some(allocate_string_on_heap(translate_newlines(text.as_str()), vm.heap)) } _ => None, }, @@ -1715,12 +1714,8 @@ fn validate_write_data(data: &Value, binary: bool, vm: &VM<'_>) -> RunResult<()> /// `None` for any other type. `write()` unwraps it after `validate_write_data`, /// `open()`'s `newline` argument uses `None` to raise its `TypeError`. pub(crate) fn extract_str_payload(data: &Value, vm: &VM<'_>) -> Option { - match data { - Value::InternString(id) => Some(vm.interns.get_str(*id).to_owned()), - Value::Ref(id) => match vm.heap.get(*id) { - HeapData::Str(s) => Some(s.as_str().to_owned()), - _ => None, - }, + match data.py_value(vm) { + PyValue::Str(text) => Some(text.as_str(vm).to_owned()), _ => None, } } @@ -1728,12 +1723,8 @@ pub(crate) fn extract_str_payload(data: &Value, vm: &VM<'_>) -> Option { /// Owned `Vec` from a value pre-validated as Python `bytes` — binary /// companion to [`extract_str_payload`]. fn extract_bytes_payload(data: &Value, vm: &VM<'_>) -> Option> { - match data { - Value::InternBytes(id) => Some(vm.interns.get_bytes(*id).to_owned()), - Value::Ref(id) => match vm.heap.get(*id) { - HeapData::Bytes(b) => Some(b.as_slice().to_owned()), - _ => None, - }, + match data.py_value(vm) { + PyValue::Bytes(bytes) => Some(bytes.as_slice(vm).to_owned()), _ => None, } } diff --git a/crates/bashkit-monty/src/types/forward_ref.rs b/crates/bashkit-monty/src/types/forward_ref.rs new file mode 100644 index 000000000..377f20402 --- /dev/null +++ b/crates/bashkit-monty/src/types/forward_ref.rs @@ -0,0 +1,946 @@ +//! `annotationlib.ForwardRef` — an annotation kept as source text. +//! +//! A `ForwardRef` is what `typing.get_type_hints(format=Format.FORWARDREF)` +//! returns for a name it cannot resolve. An unresolved name loads as a +//! stringifier, a `ForwardRef` holding the evaluation's globals: while such an +//! evaluation runs it doubles as CPython's `_Stringifier`, and subscripting, +//! attribute access, calls and operators on it build a new stringifier holding +//! the composed source text, so `Later | None` becomes `ForwardRef('Later | None')`. +//! A constructed `ForwardRef`, and any one once no evaluation runs, has the plain +//! behaviour: equality by text, `|` builds a union, and `evaluate()` compiles the text. + +use std::{ + fmt::Write, + hash::{Hash, Hasher}, + str::FromStr, +}; + +use ahash::AHasher; +use serde::{Deserialize, Serialize}; + +use crate::{ + args::{ArgValues, FromArgs}, + builtins::{Builtins, BuiltinsFunctions}, + bytecode::{CallResult, FrameGlobals, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult, SimpleException}, + frozen::{FrozenFunction, FrozenFunctions}, + hash::{HashValue, identity_hash}, + heap::{ContainsHeap, DropWithContext, HeapData, HeapId, HeapItem, HeapObjectRead, HeapReadOutput}, + intern::StaticStrings, + modules::{ModuleFunctions, StandardLib, typing}, + types::{ + BuiltinType, Dict, LazyHeapSet, PyTrait, Type, Union, + generic_alias::repr_type_arg, + str::{StringRepr, allocate_string}, + }, + value::{EitherStr, VALUE_SIZE, Value}, +}; + +/// `ForwardRef.evaluate()`: the plain `VALUE` evaluation raises as `eval()` would; +/// `FORWARDREF` returns the reference itself when the text cannot be evaluated or +/// is a bare name that stays unresolved, otherwise what the text evaluates to with +/// unresolved names as new references. +pub(crate) const EVALUATE_SOURCE: &str = r" +def __monty_forward_ref_evaluate(self, text, globals_, locals_, owner, is_class, forwardref, eval_hint, forward_ref, isinstance_, exception, syntax_error): + if not forwardref: + return eval_hint(text, globals_, locals_, False, True, 0, None, False) + try: + value = eval_hint(text, globals_, locals_, False, True, 1, owner, is_class) + except syntax_error: + raise + except exception: + return self + if isinstance_(value, forward_ref) and text.isidentifier(): + return self + return value +"; + +/// How tightly a composed text binds, from `ast.unparse`'s precedence table, so +/// embedding it in a larger expression parenthesizes `(Later | None)[int]` but +/// not `Later[int] | None`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub(crate) enum Precedence { + /// Arbitrary text of unknown shape, parenthesized wherever it is embedded. + Tuple, + /// What a call argument or subscript item demands: nothing is parenthesized. + Test, + BitOr, + BitXor, + BitAnd, + Shift, + Arith, + Term, + /// A unary `-x`, `+x` or `~x`. + Factor, + Power, + Await, + /// A name, attribute, subscript or call. + Atom, +} + +impl Precedence { + /// The next tighter level, which the non-associative side of an operator demands. + fn next(self) -> Self { + match self { + Self::Tuple => Self::Test, + Self::Test => Self::BitOr, + Self::BitOr => Self::BitXor, + Self::BitXor => Self::BitAnd, + Self::BitAnd => Self::Shift, + Self::Shift => Self::Arith, + Self::Arith => Self::Term, + Self::Term => Self::Factor, + Self::Factor => Self::Power, + Self::Power => Self::Await, + Self::Await | Self::Atom => Self::Atom, + } + } +} + +/// An `annotationlib.ForwardRef`. +/// +/// `arg`, `module` and `owner` are OWNED values (`arg` a `str`, `module` a `str` +/// or `None`, `owner` the function or class the annotation belongs to, or `None`), +/// as is a `globals` dict, so `py_dec_ref_ids` and `for_each_child_id` must +/// release and trace all four. +#[derive(Debug, Serialize, Deserialize)] +pub(crate) struct ForwardRef { + /// `__forward_arg__`, the annotation source. + arg: Value, + /// `__forward_module__`. + module: Value, + /// `__owner__`. + owner: Value, + /// `__forward_is_argument__`, compared by nothing but kept for introspection. + is_argument: bool, + /// `__forward_is_class__`: the annotation was written in a class body. + is_class: bool, + /// How tightly [`Self::arg`] binds when composed into a larger text. + precedence: Precedence, + /// The globals a stringifier was composed against (CPython's `__globals__`), + /// part of equality by identity; `None` for a constructed reference. + globals: Option, +} + +/// Arguments of `ForwardRef(arg, *, module=None, owner=None, is_argument=True, is_class=False)`. +#[derive(FromArgs)] +#[from_args(name = "ForwardRef.__init__", style = def)] +struct ForwardRefArgs { + #[from_args(static_string = "Arg")] + arg: Value, + #[from_args(kw_only, default = Value::None, static_string = "ModuleKwarg")] + module: Value, + #[from_args(kw_only, default = Value::None)] + owner: Value, + #[from_args(kw_only, default = Value::Bool(true))] + is_argument: Value, + #[from_args(kw_only, default = Value::Bool(false))] + is_class: Value, +} + +/// Arguments of `ForwardRef.evaluate(*, globals=None, locals=None, type_params=None, owner=None, format=Format.VALUE)`. +#[derive(FromArgs)] +#[from_args(name = "ForwardRef.evaluate", style = def)] +struct EvaluateArgs { + #[from_args(kw_only, default = Value::None)] + globals: Value, + #[from_args(kw_only, default = Value::None)] + locals: Value, + /// Accepted and ignored: Monty has no type parameters. + #[from_args(kw_only, default = Value::None)] + type_params: Value, + #[from_args(kw_only, default = Value::None)] + owner: Value, + #[from_args(kw_only, default = Value::Int(1))] + format: Value, +} + +impl ForwardRef { + /// `ForwardRef(arg, ...)`: `arg` must be a `str`; the keywords are stored as given. + pub(crate) fn init(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ForwardRefArgs { + arg, + module, + owner, + is_argument, + is_class, + } = ForwardRefArgs::from_args(args, vm)?; + defer_drop!(is_argument, vm); + defer_drop!(is_class, vm); + defer_drop!(arg, vm); + defer_drop!(module, vm); + defer_drop!(owner, vm); + let Some(text) = arg.as_str(vm) else { + let repr = arg.py_repr(vm)?; + defer_drop!(repr, vm); + return Err(ExcType::type_error(format!( + "Forward reference must be a string -- got {}", + repr.as_str(vm).unwrap_or_default() + ))); + }; + // Text from the constructor has no known shape, so it is always parenthesized + // when composed, unless it is a bare name. + let precedence = if is_identifier(text) { + Precedence::Atom + } else { + Precedence::Tuple + }; + // Converted before any field is cloned, so a failing `__bool__` leaks nothing. + let is_argument = is_argument.py_bool(vm)?; + let is_class = is_class.py_bool(vm)?; + let forward_ref = Self { + arg: arg.clone_with_heap(vm), + module: module.clone_with_heap(vm), + owner: owner.clone_with_heap(vm), + is_argument, + is_class, + precedence, + globals: None, + }; + Ok(Value::Ref( + vm.heap.allocate(HeapData::ForwardRef(Box::new(forward_ref))), + )) + } + + /// The stringifier a `FORWARDREF` evaluation against `globals` loads for the + /// unresolved `name`. Takes ownership of `name` (a `str`), `owner` and a `globals` dict. + pub(crate) fn stringifier(name: Value, owner: Value, is_class: bool, globals: FrameGlobals) -> Self { + Self { + arg: name, + module: Value::None, + owner, + is_argument: false, + is_class, + precedence: Precedence::Atom, + globals: Some(globals), + } + } + + /// Whether an evaluation made this reference for an unresolved name, so it + /// composes text while one runs; a constructed reference never does. + pub(crate) fn is_stringifier(&self) -> bool { + self.globals.is_some() + } + + /// `__forward_arg__`: the reference's source text, borrowed. + pub(crate) fn arg(&self) -> &Value { + &self.arg + } + + /// The globals dict this reference owns, if any. + fn globals_dict(&self) -> Option { + match self.globals { + Some(FrameGlobals::Dict(id)) => Some(id), + Some(FrameGlobals::Slots) | None => None, + } + } + + /// Invokes `on_child` for each heap id this reference owns (GC trace hook). + pub(crate) fn for_each_child_id(&self, mut on_child: impl FnMut(HeapId)) { + for value in [&self.arg, &self.module, &self.owner] { + if let Value::Ref(id) = value { + on_child(*id); + } + } + if let Some(id) = self.globals_dict() { + on_child(id); + } + } +} + +/// Releases a reference abandoned before it reaches the heap; a heap-stored one +/// is freed through [`HeapItem::py_dec_ref_ids`]. +impl DropWithContext for ForwardRef { + fn drop_with(self, ctx: &mut C) { + if let Some(id) = self.globals_dict() { + ctx.heap_mut().dec_ref(id); + } + self.arg.drop_with(ctx); + self.module.drop_with(ctx); + self.owner.drop_with(ctx); + } +} + +impl HeapItem for ForwardRef { + fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + self.arg.py_dec_ref_ids(stack); + self.module.py_dec_ref_ids(stack); + self.owner.py_dec_ref_ids(stack); + stack.extend(self.globals_dict()); + } +} + +/// Generates a pair of binary-operator hooks that compose text on a stringifier +/// and decline (`NotImplemented`) otherwise. +macro_rules! composing_binop { + ($method:ident, $reflected:ident, $op:literal, $precedence:expr) => { + fn $method(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + self.compose_binop(other, $op, $precedence, false, vm) + } + + fn $reflected(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + self.compose_binop(other, $op, $precedence, true, vm) + } + }; +} + +/// Generates a unary-operator hook that composes text on a stringifier and +/// declines otherwise. +macro_rules! composing_unary { + ($method:ident, $op:literal) => { + fn $method(&self, vm: &mut VM<'h>) -> RunResult> { + if self.composes(vm) { + let mut text = String::from($op); + self.write_operand(Precedence::Factor, vm, &mut text); + Ok(Some(self.compose(text, Precedence::Factor, vm))) + } else { + Ok(None) + } + } + }; +} + +impl<'h> HeapObjectRead<'h, ForwardRef> { + /// Whether this reference acts as a stringifier: one an evaluation made, + /// while a `FORWARDREF` evaluation is running. + fn composes(&self, vm: &VM<'h>) -> bool { + self.get(vm.heap).is_stringifier() && vm.in_forward_ref_evaluation() + } + + /// `__forward_arg__` as a Rust string. + fn text(&self, vm: &VM<'h>) -> String { + self.get(vm.heap).arg.as_str(vm).unwrap_or_default().to_owned() + } + + /// Appends this reference's text, parenthesized when `demanded` binds tighter. + fn write_operand(&self, demanded: Precedence, vm: &VM<'h>, out: &mut String) { + let text = self.text(vm); + if demanded > self.get(vm.heap).precedence { + out.push('('); + out.push_str(&text); + out.push(')'); + } else { + out.push_str(&text); + } + } + + /// A new reference holding `text`, with this one's owner, class flag and globals. + fn compose(&self, text: String, precedence: Precedence, vm: &mut VM<'h>) -> Value { + let this = self.get(vm.heap); + if let Some(id) = this.globals_dict() { + vm.heap.inc_ref(id); + } + let composed = ForwardRef { + arg: allocate_string(text, vm.heap), + module: Value::None, + owner: this.owner.clone_with_heap(vm.heap), + is_argument: false, + is_class: this.is_class, + precedence, + globals: this.globals, + }; + Value::Ref(vm.heap.allocate(HeapData::ForwardRef(Box::new(composed)))) + } + + /// `self op other` (or `other op self` when `reflected`) as composed text, + /// following `ast.unparse`'s parenthesization; `None` unless this reference [composes](Self::composes). + fn compose_binop( + &self, + other: &Value, + op: &str, + precedence: Precedence, + reflected: bool, + vm: &mut VM<'h>, + ) -> RunResult> { + if !self.composes(vm) { + return Ok(None); + } + // `**` is right-associative, so its left operand is the one that needs parentheses. + let (left, right) = if precedence == Precedence::Power { + (precedence.next(), precedence) + } else { + (precedence, precedence.next()) + }; + let mut text = String::new(); + if reflected { + render_operand(other, left, vm, &mut text)?; + write!(text, " {op} ")?; + self.write_operand(right, vm, &mut text); + } else { + self.write_operand(left, vm, &mut text); + write!(text, " {op} ")?; + render_operand(other, right, vm, &mut text)?; + } + Ok(Some(self.compose(text, precedence, vm))) + } + + /// `ForwardRef.evaluate(...)`: resolves the namespaces, then hands the text to the + /// frozen evaluator, which applies the `VALUE` / `FORWARDREF` failure rules. + fn evaluate(&self, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let EvaluateArgs { + globals, + locals, + type_params, + owner, + format, + } = EvaluateArgs::from_args(args, vm)?; + defer_drop!(globals, vm); + defer_drop!(locals, vm); + defer_drop!(type_params, vm); + defer_drop!(owner, vm); + defer_drop!(format, vm); + let (arg, module, own_owner, is_class, own_globals) = { + let this = self.get(vm.heap); + ( + this.arg.clone_with_heap(vm.heap), + this.module.clone_with_heap(vm.heap), + this.owner.clone_with_heap(vm.heap), + this.is_class, + this.globals, + ) + }; + defer_drop!(arg, vm); + defer_drop!(module, vm); + defer_drop!(own_owner, vm); + let forwardref = match format_code(format) { + Some(4) => return Ok(CallResult::Value(arg.clone_with_heap(vm))), + Some(1) => false, + Some(3) => true, + _ => { + let repr = format.py_repr(vm)?; + defer_drop!(repr, vm); + return Err(SimpleException::new_msg( + ExcType::NotImplementedError, + repr.as_str(vm).unwrap_or_default(), + ) + .into()); + } + }; + let globals = typing::namespace_dict(globals, "ForwardRef.evaluate", "globals", vm)?; + let locals = typing::namespace_dict(locals, "ForwardRef.evaluate", "locals", vm)?; + let owner = if matches!(owner, Value::None) { own_owner } else { owner }; + // As CPython: explicit globals, then `__forward_module__`'s namespace, then + // `__globals__` (the dict a stringifier was composed against), then the owner's. + let globals = if let Some(id) = globals { + vm.heap.inc_ref(id); + Value::Ref(id) + } else if let Some(module_globals) = module_globals(module, vm)? { + module_globals + } else { + match own_globals { + Some(FrameGlobals::Dict(id)) => { + vm.heap.inc_ref(id); + Value::Ref(id) + } + Some(FrameGlobals::Slots) => Value::None, + None => typing::owner_globals(owner, vm), + } + }; + defer_drop!(globals, vm); + let locals = match locals { + Some(id) => { + vm.heap.inc_ref(id); + Value::Ref(id) + } + None => typing::owner_locals(owner, vm)?, + }; + defer_drop!(locals, vm); + vm.call_frozen_exact( + FrozenFunction::ForwardRefEvaluate, + [ + self.clone_value(vm.heap), + arg.clone_with_heap(vm), + globals.clone_with_heap(vm), + locals.clone_with_heap(vm), + owner.clone_with_heap(vm), + Value::Bool(is_class), + Value::Bool(forwardref), + Value::ModuleFunction(ModuleFunctions::Frozen(FrozenFunctions::EvalHint)), + Value::Builtin(Builtins::Type(BuiltinType::ForwardRef)), + Value::Builtin(Builtins::Function(BuiltinsFunctions::Isinstance)), + Value::Builtin(Builtins::ExcType(ExcType::Exception)), + Value::Builtin(Builtins::ExcType(ExcType::SyntaxError)), + ], + ) + } +} + +/// The globals a `module=` name selects for `ForwardRef.evaluate()`, as CPython's +/// `sys.modules[module].__dict__`: `None` (the session slots) for `__main__`, a file +/// module's namespace, or a copy of a bundled module's attributes. Bundled modules +/// need no prior import; a host module or unknown name gives `Ok(None)`. +fn module_globals(module: &Value, vm: &mut VM<'_>) -> RunResult> { + let Some(name) = module.as_str(vm) else { + return Ok(None); + }; + let file_namespace = vm.modules.get_id(name).and_then(|id| match vm.heap.get(id) { + HeapData::Module(module) => module.namespace(), + _ => None, + }); + if name == "__main__" { + Ok(Some(Value::None)) + } else if let Some(namespace) = file_namespace { + vm.heap.inc_ref(namespace); + Ok(Some(Value::Ref(namespace))) + } else if let Some(bundled) = StaticStrings::from_str(name).ok().and_then(StandardLib::from_static) { + bundled_module_dict(bundled, vm).map(Some) + } else { + Ok(None) + } +} + +/// A fresh dict holding a newly created bundled module's attributes. +fn bundled_module_dict(bundled: StandardLib, vm: &mut VM<'_>) -> RunResult { + let module_id = bundled.create(vm); + let module = Value::Ref(module_id); + defer_drop!(module, vm); + let HeapData::Module(module) = vm.heap.get(module_id) else { + unreachable!("StandardLib::create allocates a module"); + }; + let pairs = module + .attrs() + .iter() + .map(|(name, value)| (name.clone_with_heap(vm.heap), value.clone_with_heap(vm.heap))) + .collect(); + let dict = Dict::from_pairs(pairs, vm)?; + Ok(Value::Ref(vm.heap.allocate(HeapData::Dict(dict)))) +} + +impl<'h> PyTrait<'h> for HeapObjectRead<'h, ForwardRef> { + fn py_type(&self, _: &VM<'h>) -> Type { + Type::ForwardRef + } + + fn py_len(&self, _: &VM<'h>) -> Option { + None + } + + /// Equal to another reference with the same text, module, class flag and + /// owner, composed against the same globals (so a reference an evaluation + /// made never equals a constructed one); `is_argument` is not compared, as in CPython. + fn py_eq_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + let Some(HeapReadOutput::ForwardRef(other)) = other.read_heap(vm) else { + return Ok(None); + }; + // The owner may itself be a reference, so a deep chain recurses. + let mut guard = vm.recursion_guard()?; + let vm = &mut *guard; + let (mine, theirs) = { + let (this, that) = (self.get(vm.heap), other.get(vm.heap)); + if this.is_class != that.is_class || this.globals != that.globals { + return Ok(Some(false)); + } + ( + [ + this.arg.clone_with_heap(vm.heap), + this.module.clone_with_heap(vm.heap), + this.owner.clone_with_heap(vm.heap), + ], + [ + that.arg.clone_with_heap(vm.heap), + that.module.clone_with_heap(vm.heap), + that.owner.clone_with_heap(vm.heap), + ], + ) + }; + defer_drop!(mine, vm); + defer_drop!(theirs, vm); + for (a, b) in mine.iter().zip(theirs) { + if !a.py_eq(b, vm)? { + return Ok(Some(false)); + } + } + Ok(Some(true)) + } + + /// Hashes what [`Self::py_eq_impl`] compares; an unhashable owner makes the + /// reference unhashable, as CPython's `hash((..., owner))` raises. + fn py_hash(&self, vm: &mut VM<'h>) -> RunResult> { + let mut guard = vm.recursion_guard()?; + let vm = &mut *guard; + let (parts, is_class, globals) = { + let this = self.get(vm.heap); + ( + [ + this.arg.clone_with_heap(vm.heap), + this.module.clone_with_heap(vm.heap), + this.owner.clone_with_heap(vm.heap), + ], + this.is_class, + this.globals, + ) + }; + defer_drop!(parts, vm); + let mut hasher = AHasher::default(); + is_class.hash(&mut hasher); + // A dict's identity is its heap id, which the hash must not persist across dumps + // under another meaning; dict and set entries rehash a reference by these parts. + match globals { + None => 0u8.hash(&mut hasher), + Some(FrameGlobals::Slots) => 1u8.hash(&mut hasher), + Some(FrameGlobals::Dict(id)) => identity_hash(id).hash(&mut hasher), + } + for part in parts { + let Some(hash) = part.py_hash(vm)? else { + return Ok(None); + }; + hash.hash(&mut hasher); + } + Ok(Some(HashValue::new(hasher.finish()))) + } + + /// `ForwardRef('Later')`, then `module=`, `is_class=True` and `owner=` when set. + /// A stringifier during a `FORWARDREF` evaluation is the bare text, as CPython's + /// `_Stringifier.__repr__`, so `f'{Later!r}'` and `str(Later)` render `Later`. + fn py_repr_fmt(&self, f: &mut impl Write, vm: &mut VM<'h>, heap_ids: &mut LazyHeapSet) -> RunResult<()> { + if self.composes(vm) { + return Ok(f.write_str(&self.text(vm))?); + } + let mut guard = vm.recursion_guard()?; + let vm = &mut *guard; + let (text, module, owner, is_class) = { + let this = self.get(vm.heap); + ( + self.text(vm), + this.module.clone_with_heap(vm.heap), + this.owner.clone_with_heap(vm.heap), + this.is_class, + ) + }; + defer_drop!(module, vm); + defer_drop!(owner, vm); + write!(f, "ForwardRef({}", StringRepr(&text))?; + if !matches!(module, Value::None) { + f.write_str(", module=")?; + module.py_repr_fmt(f, vm, heap_ids)?; + } + if is_class { + f.write_str(", is_class=True")?; + } + if !matches!(owner, Value::None) { + f.write_str(", owner=")?; + owner.py_repr_fmt(f, vm, heap_ids)?; + } + Ok(f.write_char(')')?) + } + + /// The `__forward_*__` introspection attributes; any other name composes + /// `Later.attr` on a stringifier and is an `AttributeError` otherwise. + fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> RunResult> { + let this = self.get(vm.heap); + let value = match attr.static_string(vm.interns) { + Some(StaticStrings::DunderForwardArg | StaticStrings::DunderResolvedStr) => { + this.arg.clone_with_heap(vm.heap) + } + Some(StaticStrings::DunderForwardModule) => this.module.clone_with_heap(vm.heap), + Some(StaticStrings::DunderOwner) => this.owner.clone_with_heap(vm.heap), + Some(StaticStrings::DunderForwardIsArgument) => Value::Bool(this.is_argument), + Some(StaticStrings::DunderForwardIsClass) => Value::Bool(this.is_class), + _ if self.composes(vm) => { + let mut text = String::new(); + self.write_operand(Precedence::Atom, vm, &mut text); + text.push('.'); + text.push_str(attr.as_str(vm.interns)); + self.compose(text, Precedence::Atom, vm) + } + // Named as CPython does, not by the qualified type name. + _ => return Err(ExcType::attribute_error("ForwardRef", attr.as_str(vm.interns))), + }; + Ok(Some(CallResult::Value(value))) + } + + /// `evaluate(...)`; any other method composes `Later.method(...)` on a stringifier. + fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult { + if attr.static_string(vm.interns) == Some(StaticStrings::Evaluate) { + self.evaluate(args, vm) + } else if self.composes(vm) { + let mut text = String::new(); + self.write_operand(Precedence::Atom, vm, &mut text); + text.push('.'); + text.push_str(attr.as_str(vm.interns)); + write_call(&mut text, args, vm)?; + Ok(CallResult::Value(self.compose(text, Precedence::Atom, vm))) + } else { + args.drop_with(vm); + Err(ExcType::attribute_error("ForwardRef", attr.as_str(vm.interns))) + } + } + + /// `Later(1, x=Foo)` composes on a stringifier; a plain reference is not callable. + fn py_call(&mut self, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + if self.composes(vm) { + let mut text = String::new(); + self.write_operand(Precedence::Atom, vm, &mut text); + write_call(&mut text, args, vm)?; + Ok(CallResult::Value(self.compose(text, Precedence::Atom, vm))) + } else { + args.drop_with(vm); + Err(ExcType::type_error_not_callable_object("ForwardRef")) + } + } + + /// `Later[int]`, `Later[int, str]` and `Later[1:2]` compose on a stringifier; + /// a plain reference is not subscriptable. + fn py_getitem(&self, key: &Value, vm: &mut VM<'h>) -> RunResult { + if !self.composes(vm) { + return Err(ExcType::type_error_not_sub("ForwardRef")); + } + let mut text = String::new(); + self.write_operand(Precedence::Atom, vm, &mut text); + text.push('['); + match key { + // A tuple key lists its items bare, as `ast.unparse` writes a subscript, + // keeping the `()` and trailing comma that make `Later[()]` and `Later[int,]` tuples. + Value::Ref(id) if let HeapData::Tuple(tuple) = vm.heap.get(*id) => { + let items = clone_items(tuple.as_slice(), vm)?; + defer_drop!(items, vm); + if items.is_empty() { + text.push_str("()"); + } else { + render_items(items, vm, &mut text)?; + if items.len() == 1 { + text.push(','); + } + } + } + Value::Ref(id) if let HeapData::Slice(slice) = vm.heap.get(*id) => { + let (start, stop, step) = (slice.start, slice.stop, slice.step); + for (index, bound) in [start, stop].into_iter().enumerate() { + if index > 0 { + text.push(':'); + } + if let Some(bound) = bound { + write!(text, "{bound}")?; + } + } + if let Some(step) = step { + write!(text, ":{step}")?; + } + } + _ => render_operand(key, Precedence::Test, vm, &mut text)?, + } + text.push(']'); + Ok(self.compose(text, Precedence::Atom, vm)) + } + + /// `|` composes on a stringifier; otherwise, as CPython's `ForwardRef.__or__`, + /// it builds a union with any right operand. + fn py_or_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + if let Some(composed) = self.compose_binop(other, "|", Precedence::BitOr, false, vm)? { + Ok(Some(composed)) + } else { + let members = vec![self.clone_value(vm.heap), other.clone_with_heap(vm)]; + Union::from_members(members, vm).map(Some) + } + } + + fn py_ror_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + if let Some(composed) = self.compose_binop(other, "|", Precedence::BitOr, true, vm)? { + Ok(Some(composed)) + } else { + let members = vec![other.clone_with_heap(vm), self.clone_value(vm.heap)]; + Union::from_members(members, vm).map(Some) + } + } + + composing_binop!(py_add_impl, py_radd_impl, "+", Precedence::Arith); + composing_binop!(py_sub_impl, py_rsub_impl, "-", Precedence::Arith); + composing_binop!(py_mul_impl, py_rmul_impl, "*", Precedence::Term); + composing_binop!(py_matmul_impl, py_rmatmul_impl, "@", Precedence::Term); + composing_binop!(py_truediv_impl, py_rtruediv_impl, "/", Precedence::Term); + composing_binop!(py_floordiv_impl, py_rfloordiv_impl, "//", Precedence::Term); + composing_binop!(py_mod_impl, py_rmod_impl, "%", Precedence::Term); + composing_binop!(py_lshift_impl, py_rlshift_impl, "<<", Precedence::Shift); + composing_binop!(py_rshift_impl, py_rrshift_impl, ">>", Precedence::Shift); + composing_binop!(py_and_impl, py_rand_impl, "&", Precedence::BitAnd); + composing_binop!(py_xor_impl, py_rxor_impl, "^", Precedence::BitXor); + + fn py_pow_impl(&self, other: &Value, modulus: Option<&Value>, vm: &mut VM<'h>) -> RunResult> { + if modulus.is_some() { + Ok(None) + } else { + self.compose_binop(other, "**", Precedence::Power, false, vm) + } + } + + fn py_rpow_impl(&self, other: &Value, modulus: Option<&Value>, vm: &mut VM<'h>) -> RunResult> { + if modulus.is_some() { + Ok(None) + } else { + self.compose_binop(other, "**", Precedence::Power, true, vm) + } + } + + composing_unary!(py_neg_impl, "-"); + composing_unary!(py_pos_impl, "+"); + composing_unary!(py_invert_impl, "~"); +} + +/// Appends `(a, b, k=v)` for a composed call, consuming `args`. +fn write_call(text: &mut String, args: ArgValues, vm: &mut VM<'_>) -> RunResult<()> { + let (positional, keywords) = args.into_parts(); + let positional: Vec = positional.collect(); + defer_drop!(positional, vm); + let keywords: Vec<(Value, Value)> = keywords.into_iter().collect(); + defer_drop!(keywords, vm); + text.push('('); + render_items(positional, vm, text)?; + for (index, (name, value)) in keywords.iter().enumerate() { + vm.heap.tracker.check_memory_time_every(index)?; + if index > 0 || !positional.is_empty() { + text.push_str(", "); + } + text.push_str(name.as_str(vm).unwrap_or_default()); + text.push('='); + render_operand(value, Precedence::Test, vm, text)?; + } + text.push(')'); + Ok(()) +} + +/// Appends `items` comma-separated, each rendered as an argument. The buffer +/// is allocator-backed, so the periodic poll sees it grow, as `repr()` of a +/// container is checked (see `repr_sequence_fmt`). +fn render_items(items: &[Value], vm: &mut VM<'_>, text: &mut String) -> RunResult<()> { + for (index, item) in items.iter().enumerate() { + vm.heap.tracker.check_memory_time_every(index)?; + if index > 0 { + text.push_str(", "); + } + render_operand(item, Precedence::Test, vm, text)?; + } + Ok(()) +} + +/// Appends `value` as CPython's `_Stringifier` would unparse it: another +/// stringifier by its text (parenthesized when `demanded` binds tighter), a tuple, +/// list, set or dict item by item, a type by its name and anything else, including +/// a constructed `ForwardRef`, by its repr. +fn render_operand(value: &Value, demanded: Precedence, vm: &mut VM<'_>, text: &mut String) -> RunResult<()> { + let mut guard = vm.recursion_guard()?; + let vm = &mut *guard; + let container = match value { + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::ForwardRef(forward_ref) if forward_ref.is_stringifier() => { + let inner = forward_ref.arg.as_str_heap(vm.heap, vm.interns).unwrap_or_default(); + if demanded > forward_ref.precedence { + write!(text, "({inner})")?; + } else { + text.push_str(inner); + } + return Ok(()); + } + HeapData::Tuple(tuple) => Container::Tuple(clone_items(tuple.as_slice(), vm)?), + HeapData::List(list) => Container::List(clone_items(list.as_slice(), vm)?), + HeapData::Set(set) => { + let items: Vec<&Value> = set.iter().collect(); + vm.heap + .tracker + .check_allocation(items.len().saturating_mul(VALUE_SIZE))?; + Container::Set(items.into_iter().map(|item| item.clone_with_heap(vm.heap)).collect()) + } + HeapData::Dict(dict) => { + let pairs: Vec<(&Value, &Value)> = dict.iter().collect(); + vm.heap + .tracker + .check_allocation(pairs.len().saturating_mul(2 * VALUE_SIZE))?; + Container::Dict( + pairs + .into_iter() + .map(|(k, v)| (k.clone_with_heap(vm.heap), v.clone_with_heap(vm.heap))) + .collect(), + ) + } + _ => return repr_type_arg(value, text, vm, &mut LazyHeapSet::default()), + }, + _ => return repr_type_arg(value, text, vm, &mut LazyHeapSet::default()), + }; + defer_drop!(container, vm); + match container { + Container::Tuple(items) => { + text.push('('); + render_items(items, vm, text)?; + if items.len() == 1 { + text.push(','); + } + text.push(')'); + } + Container::List(items) => { + text.push('['); + render_items(items, vm, text)?; + text.push(']'); + } + Container::Set(items) if items.is_empty() => text.push_str("set()"), + Container::Set(items) => { + text.push('{'); + render_items(items, vm, text)?; + text.push('}'); + } + Container::Dict(pairs) => { + text.push('{'); + for (index, (key, value)) in pairs.iter().enumerate() { + vm.heap.tracker.check_memory_time_every(index)?; + if index > 0 { + text.push_str(", "); + } + render_operand(key, Precedence::Test, vm, text)?; + text.push_str(": "); + render_operand(value, Precedence::Test, vm, text)?; + } + text.push('}'); + } + } + Ok(()) +} + +/// Owned clones of a container's items, taken before rendering them so the +/// heap borrow ends first. +enum Container { + Tuple(Vec), + List(Vec), + Set(Vec), + Dict(Vec<(Value, Value)>), +} + +impl DropWithContext for Container { + fn drop_with(self, ctx: &mut C) { + match self { + Self::Tuple(items) | Self::List(items) | Self::Set(items) => items.drop_with(ctx), + Self::Dict(pairs) => pairs.drop_with(ctx), + } + } +} + +/// Owned clones of `items`, preflighted against the memory limit. +fn clone_items(items: &[Value], vm: &VM<'_>) -> RunResult> { + vm.heap + .tracker + .check_allocation(items.len().saturating_mul(VALUE_SIZE))?; + Ok(items.iter().map(|item| item.clone_with_heap(vm.heap)).collect()) +} + +/// The `Format` member `value` names, `None` for anything else. CPython compares +/// with `==`, so a bool or a whole float (`4.0`) names the member too. +pub(crate) fn format_code(value: &Value) -> Option { + match value { + Value::Int(code) => Some(*code), + Value::Bool(flag) => Some(i64::from(*flag)), + Value::Float(code) => whole_float_code(*code), + _ => None, + } +} + +/// A small whole float as its int; `None` for a fraction or anything beyond the members. +#[expect(clippy::cast_possible_truncation, reason = "a whole float below 16 converts exactly")] +fn whole_float_code(code: f64) -> Option { + (code.fract() == 0.0 && code.abs() < 16.0).then_some(code as i64) +} + +/// Whether `text` is a plain Python identifier, which `ForwardRef.evaluate()` +/// looks up as a name rather than compiling. +fn is_identifier(text: &str) -> bool { + let mut chars = text.chars(); + chars.next().is_some_and(|first| first == '_' || first.is_alphabetic()) + && chars.all(|c| c == '_' || c.is_alphanumeric()) +} diff --git a/crates/bashkit-monty/src/types/generic_alias.rs b/crates/bashkit-monty/src/types/generic_alias.rs index ed8a12225..90b8e0a5d 100644 --- a/crates/bashkit-monty/src/types/generic_alias.rs +++ b/crates/bashkit-monty/src/types/generic_alias.rs @@ -1,46 +1,77 @@ //! `types.GenericAlias` — the runtime value of `list[int]`, `dict[str, int]`, -//! `tuple[int, ...]` and the other parameterized builtin types. +//! `tuple[int, ...]` and the other parameterized builtin types — and, sharing +//! the type, CPython's `typing._GenericAlias`: `typing.List[int]`, +//! `ClassVar[int]`, `Annotated[int, 'meta']` and the other subscripted +//! `typing` special forms. //! -//! An alias records which type was subscripted and with what, and otherwise -//! behaves like the type it parameterizes: calling `list[int](x)` calls -//! `list(x)`, and any attribute other than `__origin__`, `__args__` and +//! An alias records which type or form was subscripted and with what, and +//! otherwise behaves like the type it parameterizes: calling `list[int](x)` +//! calls `list(x)`, and any attribute other than `__origin__`, `__args__` and //! `__parameters__` is looked up on the origin. Nothing inspects the //! arguments, so `list[int]` and `list[3.5]` are equally valid, as in CPython. use std::{ fmt::Write, hash::{Hash, Hasher}, + mem, }; -use ahash::AHasher; +use ahash::{AHashMap, AHasher}; use serde::{Deserialize, Serialize}; -use smallvec::smallvec; +use smallvec::{SmallVec, smallvec}; use crate::{ - args::ArgValues, + args::{ArgValues, FromArgs}, builtins::{Builtins, BuiltinsFunctions}, bytecode::{CallResult, VM}, - defer_drop, - exception_private::{ExcType, ExcTypeExt, RunResult}, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunResult, SimpleException}, hash::HashValue, - heap::{ContainsHeap, DropWithContext, HeapData, HeapId, HeapItem, HeapObjectRead, HeapReadOutput}, + heap::{ + ContainsHeap, DropGuard, DropWithContext, Heap, HeapData, HeapId, HeapItem, HeapObjectRead, HeapReadOutput, + }, intern::StaticStrings, - types::{LazyHeapSet, PyTrait, Type, Union, instance::class_name, list::repr_check_time, tuple::allocate_tuple}, - value::{EitherStr, Value}, + types::{ + BuiltinType, LazyHeapSet, PyTrait, Type, Union, + instance::class_name, + list::repr_should_truncate, + set::unhashable_type_name, + tuple::{TupleVec, allocate_tuple}, + }, + value::{EitherStr, Marker, VALUE_SIZE, Value}, }; -/// A parameterized builtin type such as `list[int]`. +/// The origin of `typing.Literal[...]`, whose values compare as a set. +const LITERAL: AliasOrigin = AliasOrigin::Special(Marker(StaticStrings::Literal)); + +/// The origin of `typing.Callable[[params], result]`, stored flattened as `(params..., result)`. +const CALLABLE: AliasOrigin = AliasOrigin::Special(Marker(StaticStrings::Callable)); + +/// What an alias parameterizes: a builtin type (`list[int]`) or a `typing` +/// special form (`typing.List[int]`, `ClassVar[int]`), CPython's +/// `types.GenericAlias` and `typing._GenericAlias` in one type. Untagged so a +/// builtin origin dumps as the bare type it always did. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum AliasOrigin { + /// A builtin type satisfying [`Type::has_class_getitem`]; never a class object. + Builtin(BuiltinType), + /// A `typing` marker satisfying [`Marker::is_generic_form`]. + Special(Marker), +} + +/// A parameterized builtin type such as `list[int]`, or `typing` form such as `List[int]`. /// /// `args` is an OWNED ref to the `__args__` tuple — the subscript itself when /// it was a tuple (`dict[str, int]`), otherwise a one-item tuple wrapping it — -/// so `py_dec_ref_ids` and `for_each_child_id` must both release it. +/// so `py_dec_ref_ids` and `for_each_child_id` must both release it. For +/// `Annotated[T, *metadata]` it holds `T` and the metadata together, which +/// `__args__` and `__metadata__` split. #[derive(Debug, Serialize, Deserialize)] pub(crate) struct GenericAlias { - /// The subscripted type, `list` in `list[int]`. Never a class object: - /// only the builtin types in [`Type::has_class_getitem`] are subscriptable. - origin: Type, - /// The `__args__` tuple, always a `Value::Ref` to a `HeapData::Tuple`, - /// shared with every read of that attribute. + /// The subscripted type or form, `list` in `list[int]`. + origin: AliasOrigin, + /// The subscript as a tuple, always a `Value::Ref` to a `HeapData::Tuple`. args: Value, } @@ -49,8 +80,57 @@ impl GenericAlias { /// /// `origin` must satisfy [`Type::has_class_getitem`]; callers raise the /// `type 'int' is not subscriptable` error for the rest. - pub(crate) fn subscript(origin: Type, key: Value, vm: &mut VM<'_>) -> Value { - debug_assert!(origin.has_class_getitem(), "{origin} is not a generic type"); + pub(crate) fn subscript(origin: BuiltinType, key: Value, vm: &mut VM<'_>) -> Value { + debug_assert!(Type::from(origin).has_class_getitem(), "{origin} is not a generic type"); + Self::allocate(AliasOrigin::Builtin(origin), key, vm) + } + + /// Builds `typing.Form[key]` for a form satisfying [`Marker::is_generic_form`], + /// taking ownership of `key`, with the argument checks CPython makes. + pub(crate) fn subscript_special(form: Marker, key: Value, vm: &mut VM<'_>) -> RunResult { + debug_assert!(form.is_generic_form(), "{form:?} is not subscriptable"); + let mut key_guard = DropGuard::new(key, vm); + let (key, vm) = key_guard.as_parts(); + let count = match key { + Value::Ref(id) if let HeapData::Tuple(items) = vm.heap.get(*id) => items.as_slice().len(), + _ => 1, + }; + match form.0 { + StaticStrings::Annotated if count < 2 => { + return Err(ExcType::type_error( + "Annotated[...] should be used with at least two arguments (a type and an annotation).", + )); + } + StaticStrings::ClassVar | StaticStrings::FinalType if count != 1 => { + let repr = key.py_repr(vm)?; + defer_drop!(repr, vm); + return Err(ExcType::type_error(format!( + "typing.{} accepts only single type. Got {}.", + <&str>::from(form.0), + repr.as_str(vm).unwrap_or_default() + ))); + } + StaticStrings::Callable if count != 2 => { + return Err(ExcType::type_error( + "Callable must be used as Callable[[arg, ...], result].", + )); + } + _ => {} + } + let (key, vm) = key_guard.into_parts(); + // `typing` forms normalise a `None` argument to `NoneType`, as CPython's + // `_type_check` does — except `Literal` values and `Annotated` metadata. + let key = match form.0 { + StaticStrings::Literal => literal_params(key, vm)?, + StaticStrings::Annotated => flatten_annotated(none_to_none_type(key, 1, vm)?, vm)?, + StaticStrings::Callable => none_to_none_type(callable_params(key, vm)?, usize::MAX, vm)?, + _ => none_to_none_type(key, usize::MAX, vm)?, + }; + Ok(Self::allocate(AliasOrigin::Special(form), key, vm)) + } + + /// Allocates the alias, wrapping a non-tuple `key` as a one-item `__args__`. + fn allocate(origin: AliasOrigin, key: Value, vm: &mut VM<'_>) -> Value { // A tuple key is `__args__` itself, as in CPython, so `tuple[()]` // has empty args and `list[int, str]` two. let is_tuple = matches!(&key, Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::Tuple(_))); @@ -62,18 +142,51 @@ impl GenericAlias { Value::Ref(vm.heap.allocate(HeapData::GenericAlias(Self { origin, args }))) } - /// The value `__origin__` reports and a call dispatches to. + /// The subscripted type or form. + pub(crate) fn origin(&self) -> AliasOrigin { + self.origin + } + + /// The value `__origin__` reports and a call dispatches to, as an owned value. /// /// `type` is a builtin function rather than a `Type` value in Monty, so /// `type[int]` hands back that function: `type[int].__origin__ is type` - /// holds and `type[int](x)` reaches `type()`. - pub(crate) fn origin_value(&self) -> Value { + /// holds and `type[int](x)` reaches `type()`. A `typing` alias of a builtin + /// (`typing.List[int]`) reports that builtin; `Annotated[T, ...]` reports + /// `T`; the other forms report themselves. + pub(crate) fn origin_value(&self, heap: &Heap) -> Value { match self.origin { - Type::Type => Value::Builtin(Builtins::Function(BuiltinsFunctions::Type)), - origin => Value::Builtin(Builtins::Type(origin)), + AliasOrigin::Builtin(BuiltinType::Type) => Value::Builtin(Builtins::Function(BuiltinsFunctions::Type)), + AliasOrigin::Builtin(origin) => Value::Builtin(Builtins::Type(origin)), + AliasOrigin::Special(form) => match form.0 { + StaticStrings::ListType => Value::Builtin(Builtins::Type(BuiltinType::List)), + StaticStrings::DictType => Value::Builtin(Builtins::Type(BuiltinType::Dict)), + StaticStrings::TupleType => Value::Builtin(Builtins::Type(BuiltinType::Tuple)), + StaticStrings::SetType => Value::Builtin(Builtins::Type(BuiltinType::Set)), + StaticStrings::FrozenSet => Value::Builtin(Builtins::Type(BuiltinType::FrozenSet)), + StaticStrings::Type => Value::Builtin(Builtins::Function(BuiltinsFunctions::Type)), + StaticStrings::Annotated => self.annotated_type(heap), + _ => Value::Marker(form), + }, } } + /// Whether this is `Annotated[T, *metadata]`. + fn is_annotated(&self) -> bool { + matches!(self.origin, AliasOrigin::Special(Marker(StaticStrings::Annotated))) + } + + /// The `T` of `Annotated[T, *metadata]`, owned. + fn annotated_type(&self, heap: &Heap) -> Value { + let Value::Ref(id) = self.args else { + unreachable!("GenericAlias::args is always a tuple") + }; + let HeapData::Tuple(items) = heap.get(id) else { + unreachable!("GenericAlias::args is always a tuple") + }; + items.as_slice()[0].clone_with_heap(heap) + } + /// Invokes `on_child` for the heap id this alias owns (GC trace hook). pub(crate) fn for_each_child_id(&self, mut on_child: impl FnMut(HeapId)) { if let Value::Ref(id) = self.args { @@ -97,12 +210,23 @@ impl HeapItem for GenericAlias { } impl<'h> HeapObjectRead<'h, GenericAlias> { - /// The origin type and an owned ref to the `__args__` tuple. - fn parts(&self, vm: &mut VM<'h>) -> (Type, Value) { + /// The origin and an owned ref to the stored args tuple. + fn parts(&self, vm: &mut VM<'h>) -> (AliasOrigin, Value) { let this = self.get(vm.heap); (this.origin, this.args.clone_with_heap(vm)) } + /// `__args__`, owned: the stored tuple, or for `Annotated` its type alone. + fn dunder_args(&self, vm: &mut VM<'h>) -> Value { + let this = self.get(vm.heap); + if this.is_annotated() { + let item = this.annotated_type(vm.heap); + allocate_tuple(smallvec![item], vm.heap) + } else { + this.args.clone_with_heap(vm) + } + } + /// The alias's repr as a plain string, for error messages that name it. fn repr_string(&self, vm: &mut VM<'h>) -> RunResult { let mut repr = String::new(); @@ -113,10 +237,40 @@ impl<'h> HeapObjectRead<'h, GenericAlias> { impl<'h> PyTrait<'h> for HeapObjectRead<'h, GenericAlias> { /// `list[int](x)` is `list(x)`: the subscript is erased at runtime, so the - /// arguments go straight to the origin type. + /// arguments go straight to the origin type. A `typing` form refuses, with + /// CPython's message for a bare generic, an abstract class or a special form. fn py_call(&mut self, args: ArgValues, vm: &mut VM<'h>) -> RunResult { - let origin = self.get(vm.heap).origin_value(); - vm.call_function(&origin, args) + let this = self.get(vm.heap); + if let AliasOrigin::Special(form) = this.origin + && !this.is_annotated() + { + args.drop_with(vm); + let name: &str = form.0.into(); + let message = match form.0 { + StaticStrings::ListType + | StaticStrings::DictType + | StaticStrings::TupleType + | StaticStrings::SetType + | StaticStrings::FrozenSet + | StaticStrings::Type => { + format!( + "Type {name} cannot be instantiated; use {}() instead", + name.to_lowercase() + ) + } + StaticStrings::Callable => abstract_class_error(name, "'__call__'"), + StaticStrings::Sequence => abstract_class_error(name, "'__getitem__', '__len__'"), + StaticStrings::Mapping => abstract_class_error(name, "'__getitem__', '__iter__', '__len__'"), + StaticStrings::Iterable => abstract_class_error(name, "'__iter__'"), + StaticStrings::IteratorType => abstract_class_error(name, "'__next__'"), + StaticStrings::Generator => abstract_class_error(name, "'send', 'throw'"), + _ => format!("Cannot instantiate typing.{name}"), + }; + return Err(ExcType::type_error(message)); + } + let origin = this.origin_value(vm.heap); + defer_drop!(origin, vm); + vm.call_function(origin, args) } fn py_type(&self, _: &VM<'h>) -> Type { @@ -127,7 +281,8 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, GenericAlias> { None } - /// Two aliases are equal when their origins and `__args__` are. + /// Two aliases are equal when their origins and `__args__` are; `Literal` + /// compares its values as a set, as CPython does. /// /// Takes a recursion level like the repr: an argument can be a list that /// holds this alias, and comparing two such cycles raises `RecursionError` @@ -142,20 +297,37 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, GenericAlias> { defer_drop!(args, vm); let (other_origin, other_args) = other.parts(vm); defer_drop!(other_args, vm); - Ok(Some(origin == other_origin && args.py_eq(other_args, vm)?)) + if origin != other_origin { + Ok(Some(false)) + } else if origin == LITERAL { + literal_eq(args, other_args, vm).map(Some) + } else { + args.py_eq(other_args, vm).map(Some) + } } /// Combines the origin with the `__args__` tuple's hash, so `list[int]` /// is one dict key however many times it is written; an unhashable /// argument (`list[[1]]`) makes the alias unhashable, as in CPython. + /// `Literal` hashes its values in any order, matching its equality. fn py_hash(&self, vm: &mut VM<'h>) -> RunResult> { let (origin, args) = self.parts(vm); defer_drop!(args, vm); - let Some(args_hash) = args.py_hash(vm)? else { + let args_hash = if origin == LITERAL { + literal_hash(args, vm)? + } else { + args.py_hash(vm)? + }; + let Some(args_hash) = args_hash else { return Ok(None); }; let mut hasher = AHasher::default(); - origin.hash(&mut hasher); + // Dicts and sets persist hashes: a builtin origin hashes by Type's + // original discriminant, a form by its name, which never move. + match origin { + AliasOrigin::Builtin(origin) => Type::from(origin).hash(&mut hasher), + AliasOrigin::Special(form) => <&str>::from(form.0).hash(&mut hasher), + } args_hash.hash(&mut hasher); Ok(Some(HashValue::new(hasher.finish()))) } @@ -175,38 +347,101 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, GenericAlias> { unreachable!("GenericAlias::args is always a tuple") }; - write!(f, "{}[", origin.name(vm.heap, vm.interns))?; + match origin { + AliasOrigin::Builtin(origin) => write!(f, "{}[", Type::from(origin).name(vm.heap, vm.interns))?, + AliasOrigin::Special(form) => { + form.py_repr_fmt(f)?; + f.write_char('[')?; + } + } let count = args.get(vm.heap).as_slice().len(); if count == 0 { f.write_str("()")?; } + // `Callable` stores `(params..., result)` and prints the parameter list. + let (list_end, list_only) = if origin == CALLABLE && count > 0 { + let first = args.clone_item(0, vm); + defer_drop!(first, vm); + if count == 2 && matches!(first, Value::Ellipsis) { + (0, false) + } else { + f.write_char('[')?; + (count - 1, count == 1) + } + } else { + (0, false) + }; + if list_only { + f.write_str("], ")?; + } for index in 0..count { if index > 0 { - // bashkit fork: `?` so a time hit errors instead of truncating (see `repr_check_time`). - if repr_check_time(index, vm)? { + if repr_should_truncate(index, vm)? { f.write_str(", ...[timeout]")?; break; } - f.write_str(", ")?; + f.write_str(if index == list_end { "], " } else { ", " })?; } let item = args.clone_item(index, vm); defer_drop!(item, vm); - repr_type_arg(item, f, vm, heap_ids)?; + if !repr_list_arg(item, f, vm, heap_ids)? { + repr_type_arg(item, f, vm, heap_ids)?; + } } Ok(f.write_char(']')?) } - /// `__origin__`, `__args__` and `__parameters__` (always `()`, Monty - /// having no `TypeVar`s); everything else resolves on the origin type, so - /// `list[int].__name__` is `'list'` and unknown names report `list`. + /// `__origin__`, `__args__`, `__parameters__` (always `()`, Monty having + /// no `TypeVar`s) and, for `Annotated`, `__metadata__`; everything else + /// resolves on a builtin origin type, so `list[int].__name__` is `'list'` + /// and unknown names report `list`, and is an error on a `typing` form. fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> RunResult> { - let (origin, args) = self.parts(vm); - defer_drop!(args, vm); + let origin = self.get(vm.heap).origin; match attr.static_string(vm.interns) { - Some(StaticStrings::DunderOrigin) => Ok(Some(CallResult::Value(self.get(vm.heap).origin_value()))), - Some(StaticStrings::DunderArgs) => Ok(Some(CallResult::Value(args.clone_with_heap(vm)))), + Some(StaticStrings::DunderOrigin) => Ok(Some(CallResult::Value(self.get(vm.heap).origin_value(vm.heap)))), + Some(StaticStrings::DunderArgs) => Ok(Some(CallResult::Value(self.dunder_args(vm)))), Some(StaticStrings::DunderParameters) => Ok(Some(CallResult::Value(vm.heap.get_empty_tuple()))), - _ => Value::Builtin(Builtins::Type(origin)).py_getattr(attr, vm).map(Some), + Some(StaticStrings::DunderMetadata) if self.get(vm.heap).is_annotated() => { + let (_, args) = self.parts(vm); + defer_drop!(args, vm); + let Some(HeapReadOutput::Tuple(args)) = args.read_heap(vm) else { + unreachable!("GenericAlias::args is always a tuple") + }; + let count = args.get(vm.heap).as_slice().len() - 1; + vm.heap.tracker.check_allocation(count.saturating_mul(VALUE_SIZE))?; + let metadata = args.get(vm.heap).as_slice()[1..] + .iter() + .map(|item| item.clone_with_heap(vm.heap)) + .collect(); + Ok(Some(CallResult::Value(allocate_tuple(metadata, vm.heap)))) + } + _ => match origin { + AliasOrigin::Builtin(origin) => Value::Builtin(Builtins::Type(origin)).py_getattr(attr, vm).map(Some), + // CPython's `_BaseGenericAlias.__getattr__`: a dunder raises with + // the bare name, anything else is looked up on the origin. + AliasOrigin::Special(_) => { + let name = attr.as_str(vm.interns); + if is_dunder(name) { + Err(SimpleException::new_msg(ExcType::AttributeError, name).into()) + } else { + let origin = self.get(vm.heap).origin_value(vm.heap); + defer_drop!(origin, vm); + match origin { + // The forms standing in for a `collections.abc` class + // report it as the class CPython forwards to. + Value::Marker(form) if is_abc_form(*form) => { + Err(ExcType::attribute_error_type(form.0.into(), name)) + } + // A special form (`ClassVar`, `Literal`, `NoReturn`) raises the + // bare name too, as CPython's `_SpecialForm.__getattr__` does. + Value::Marker(form) if form.py_type() == Type::SpecialForm => { + Err(SimpleException::new_msg(ExcType::AttributeError, name).into()) + } + _ => origin.py_getattr(attr, vm).map(Some), + } + } + } + }, } } @@ -215,23 +450,37 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, GenericAlias> { /// dispatch to the origin's classmethods, and `list[int].__name__()` to /// the origin's own attributes. fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult { - if matches!( + let own_attribute = matches!( attr.static_string(vm.interns), - Some(StaticStrings::DunderOrigin | StaticStrings::DunderArgs | StaticStrings::DunderParameters) - ) { - let Some(CallResult::Value(value)) = self.py_getattr(attr, vm)? else { - unreachable!("the alias's own attributes are always plain values") - }; - defer_drop!(value, vm); - return vm.call_function(value, args); - } - let origin = self.get(vm.heap).origin; - match attr { - EitherStr::Interned(method_id) => origin.call_class_method(*method_id, args, vm), - // Classmethod names are all interned, so a heap string never names one. - EitherStr::Heap(name) => { - args.drop_with(vm); - Err(ExcType::attribute_error_type(&origin.name(vm.heap, vm.interns), name)) + Some( + StaticStrings::DunderOrigin + | StaticStrings::DunderArgs + | StaticStrings::DunderParameters + | StaticStrings::DunderMetadata + ) + ); + let origin = self.get(vm.heap).origin_value(vm.heap); + defer_drop!(origin, vm); + match self.get(vm.heap).origin { + AliasOrigin::Builtin(origin) if !own_attribute => Type::from(origin).call_class_method(attr, args, vm), + // A `typing` form's origin answers the call itself: a host class's + // lookup may suspend for the host, which only a call-attr carries. A + // form's own markers take the lookup path below, for its errors. + AliasOrigin::Special(_) + if !own_attribute && !is_dunder(attr.as_str(vm.interns)) && !matches!(origin, Value::Marker(_)) => + { + origin.py_value(vm).py_call_attr(vm, attr, args) + } + _ => { + // The guard releases `args` when the attribute lookup fails. + let mut args_guard = DropGuard::new(args, vm); + let (_, vm) = args_guard.as_parts_mut(); + let Some(CallResult::Value(value)) = self.py_getattr(attr, vm)? else { + unreachable!("the alias's own attributes and a dunder's error are plain values") + }; + let (args, vm) = args_guard.into_parts(); + defer_drop!(value, vm); + vm.call_function(value, args) } } } @@ -252,6 +501,367 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, GenericAlias> { } } +/// Replaces `None` with `NoneType` in the first `limit` items of a subscript +/// (`key` itself when it is not a tuple), taking and returning ownership. The +/// copy is preflighted like any container copy. +fn none_to_none_type(key: Value, limit: usize, vm: &mut VM<'_>) -> RunResult { + let none_type = || Value::Builtin(Builtins::Type(BuiltinType::NoneType)); + // The reader on `key` must be released before `key`, possibly the last + // reference to a fresh tuple, is dropped below. + let converted = { + let Some(HeapReadOutput::Tuple(items)) = key.read_heap(vm) else { + return Ok(if matches!(key, Value::None) { none_type() } else { key }); + }; + let count = items.get(vm.heap).as_slice().len(); + if let Err(err) = vm.heap.tracker.check_allocation(count.saturating_mul(VALUE_SIZE)) { + drop(items); + key.drop_with(vm); + return Err(err.into()); + } + let mut converted = smallvec![]; + for index in 0..count { + let item = items.clone_item(index, vm); + converted.push(if index < limit && matches!(item, Value::None) { + none_type() + } else { + item + }); + } + converted + }; + key.drop_with(vm); + Ok(allocate_tuple(converted, vm.heap)) +} + +/// `Annotated[Annotated[T, a], b]` is `Annotated[T, a, b]`: nested metadata +/// flattens, innermost first, as CPython's `Annotated.__class_getitem__` does. +/// Takes and returns ownership of the args tuple. +fn flatten_annotated(key: Value, vm: &mut VM<'_>) -> RunResult { + defer_drop!(key, vm); + // The readers on `key` must be released before it can be dropped. + let flattened = { + let Some(HeapReadOutput::Tuple(items)) = key.read_heap(vm) else { + unreachable!("Annotated takes at least two arguments") + }; + let first = items.clone_item(0, vm); + defer_drop!(first, vm); + match first.read_heap(vm) { + Some(HeapReadOutput::GenericAlias(inner)) if inner.get(vm.heap).is_annotated() => { + let (_, inner_args) = inner.parts(vm); + defer_drop!(inner_args, vm); + let Some(HeapReadOutput::Tuple(inner_items)) = inner_args.read_heap(vm) else { + unreachable!("GenericAlias::args is always a tuple") + }; + let count = items.get(vm.heap).as_slice().len(); + let inner_count = inner_items.get(vm.heap).as_slice().len(); + // One preflight for the whole buffer: the inner alias's args + // plus this subscript's metadata. + vm.heap + .tracker + .check_allocation((inner_count + count - 1).saturating_mul(VALUE_SIZE))?; + let mut flattened = TupleVec::with_capacity(inner_count + count - 1); + for index in 0..inner_count { + flattened.push(inner_items.clone_item(index, vm)); + } + for index in 1..count { + flattened.push(items.clone_item(index, vm)); + } + Some(flattened) + } + _ => None, + } + }; + Ok(match flattened { + Some(flattened) => allocate_tuple(flattened, vm.heap), + None => key.clone_with_heap(vm), + }) +} + +/// `Literal`'s parameters as CPython stores them: a nested `Literal` is +/// flattened into its values and duplicates are dropped, where `1` and `True` +/// are distinct values. Takes ownership of `key` and returns the args tuple. +fn literal_params(key: Value, vm: &mut VM<'_>) -> RunResult { + defer_drop!(key, vm); + let written = if matches!(key.read_heap(vm), Some(HeapReadOutput::Tuple(_))) { + tuple_items(key, vm)? + } else { + smallvec![key.clone_with_heap(vm)] + }; + // One level of flattening: a nested `Literal` was normalised when it was + // built. The flattened buffer and the deduplicated one it feeds are + // preflighted together; values are taken out of `written` one at a time and + // `flattened` is guarded from the start, so a refused copy leaks nothing. + defer_drop_mut!(written, vm); + let mut total = 0usize; + for value in written.iter() { + total = total.saturating_add(nested_literal_len(value, vm).unwrap_or(1)); + } + vm.heap.tracker.check_allocation(total.saturating_mul(2 * VALUE_SIZE))?; + let mut flattened_guard = DropGuard::new(TupleVec::with_capacity(total), vm); + let (flattened, vm) = flattened_guard.as_parts_mut(); + for index in 0..written.len() { + vm.heap.tracker.check_time_every(index)?; + let value = mem::replace(&mut written[index], Value::None); + let nested = match value.read_heap(vm) { + Some(HeapReadOutput::GenericAlias(alias)) if alias.get(vm.heap).origin == LITERAL => { + Some(alias.parts(vm).1) + } + _ => None, + }; + match nested { + Some(args) => { + defer_drop!(args, vm); + value.drop_with(vm); + flattened.extend(tuple_items(args, vm)?); + } + None => flattened.push(value), + } + } + let (flattened, vm) = flattened_guard.into_parts(); + // Values are taken out one at a time, so the guard still releases the rest + // when a comparison fails. Hashable values are bucketed by type and hash, + // keeping deduplication linear; unhashable ones are compared one by one. + defer_drop_mut!(flattened, vm); + let mut params_guard = DropGuard::new(TupleVec::new(), vm); + let (params, vm) = params_guard.as_parts_mut(); + let mut buckets: AHashMap<(Type, u64), SmallVec<[usize; 1]>> = AHashMap::new(); + let mut unhashable: Vec = Vec::new(); + for index in 0..flattened.len() { + vm.heap.tracker.check_time_every(index)?; + let value = mem::replace(&mut flattened[index], Value::None); + let mut value_guard = DropGuard::new(value, vm); + let (value, vm) = value_guard.as_parts_mut(); + let bucket = value.py_hash(vm)?.map(|hash| (value.py_type(vm), hash.raw())); + let candidates = match &bucket { + Some(key) => buckets.get(key).map_or(&[][..], SmallVec::as_slice), + None => unhashable.as_slice(), + }; + let mut duplicate = false; + for &candidate in candidates { + if same_literal_value(¶ms[candidate], value, vm)? { + duplicate = true; + break; + } + } + if !duplicate { + let (value, _) = value_guard.into_parts(); + let position = params.len(); + params.push(value); + match bucket { + Some(key) => buckets.entry(key).or_default().push(position), + None => unhashable.push(position), + } + } + } + let (params, vm) = params_guard.into_parts(); + Ok(allocate_tuple(params, vm.heap)) +} + +/// How many values a nested `Literal` contributes when flattened; `None` for +/// any other value, which contributes itself. +fn nested_literal_len(value: &Value, vm: &VM<'_>) -> Option { + let Value::Ref(id) = value else { return None }; + let HeapData::GenericAlias(alias) = vm.heap.get(*id) else { + return None; + }; + if alias.origin != LITERAL { + return None; + } + let Value::Ref(args) = alias.args else { + unreachable!("GenericAlias::args is always a tuple") + }; + let HeapData::Tuple(items) = vm.heap.get(args) else { + unreachable!("GenericAlias::args is always a tuple") + }; + Some(items.as_slice().len()) +} + +/// Whether two `Literal` values are one parameter: equal and of one type, so +/// `Literal[1]` and `Literal[True]` differ, as in CPython. +fn same_literal_value(a: &Value, b: &Value, vm: &mut VM<'_>) -> RunResult { + Ok(a.py_type(vm) == b.py_type(vm) && a.py_eq(b, vm)?) +} + +/// `Literal` equality: the same values in any order, both sides already +/// deduplicated. An unhashable value raises the `TypeError` CPython's set +/// comparison does. +fn literal_eq(args: &Value, other_args: &Value, vm: &mut VM<'_>) -> RunResult { + let items = tuple_items(args, vm)?; + defer_drop!(items, vm); + let others = tuple_items(other_args, vm)?; + defer_drop!(others, vm); + // Bucket the other side by type and hash, so the comparison is linear. + let mut buckets: AHashMap<(Type, u64), SmallVec<[usize; 1]>> = AHashMap::new(); + for (index, item) in items.iter().chain(others.iter()).enumerate() { + vm.heap.tracker.check_time_every(index)?; + let Some(hash) = item.py_hash(vm)? else { + let unhashable_type = unhashable_type_name(item, vm)?; + return Err(ExcType::type_error_unhashable_set_element("tuple", &unhashable_type)); + }; + if index >= items.len() { + buckets + .entry((item.py_type(vm), hash.raw())) + .or_default() + .push(index - items.len()); + } + } + if items.len() != others.len() { + return Ok(false); + } + for (index, item) in items.iter().enumerate() { + vm.heap.tracker.check_time_every(index)?; + let Some(hash) = item.py_hash(vm)? else { + unreachable!("checked above") + }; + let mut found = false; + for &candidate in buckets + .get(&(item.py_type(vm), hash.raw())) + .map_or(&[][..], SmallVec::as_slice) + { + if same_literal_value(item, &others[candidate], vm)? { + found = true; + break; + } + } + if !found { + return Ok(false); + } + } + Ok(true) +} + +/// `Literal`'s argument hash: each value's hash paired with its type, as the +/// equality pairs them, combined in any order; `None` when a value is unhashable. +fn literal_hash(args: &Value, vm: &mut VM<'_>) -> RunResult> { + let items = tuple_items(args, vm)?; + defer_drop!(items, vm); + let mut combined: u64 = 0; + for (index, item) in items.iter().enumerate() { + vm.heap.tracker.check_time_every(index)?; + let Some(hash) = item.py_hash(vm)? else { + return Ok(None); + }; + let mut hasher = AHasher::default(); + item.py_type(vm).hash(&mut hasher); + hash.hash(&mut hasher); + combined = combined.wrapping_add(hasher.finish()); + } + Ok(Some(HashValue::new(combined))) +} + +/// `Callable[[a, b], r]` stores `(a, b, r)`, as CPython's `_CallableGenericAlias` +/// does: a parameter list flattens, while `...` and a single bare parameter +/// stand alone. Takes ownership of the `(params, result)` pair; the copy of +/// the list is preflighted like any container copy. +fn callable_params(key: Value, vm: &mut VM<'_>) -> RunResult { + defer_drop!(key, vm); + let Some(HeapReadOutput::Tuple(pair)) = key.read_heap(vm) else { + unreachable!("Callable takes a parameter list and a result") + }; + let params = pair.clone_item(0, vm); + defer_drop!(params, vm); + let mut flattened = if let Some(HeapReadOutput::List(list)) = params.read_heap(vm) { + let count = list.get(vm.heap).as_slice().len(); + vm.heap.tracker.check_allocation(count.saturating_mul(VALUE_SIZE))?; + (0..count).map(|index| list.clone_item(index, vm)).collect::() + } else { + smallvec![params.clone_with_heap(vm)] + }; + flattened.push(pair.clone_item(1, vm)); + Ok(allocate_tuple(flattened, vm.heap)) +} + +/// Whether `name` is a `__dunder__`, which CPython's alias never forwards to its origin. +fn is_dunder(name: &str) -> bool { + name.len() > 4 && name.starts_with("__") && name.ends_with("__") +} + +/// Whether `form` stands in for a `collections.abc` class in CPython +/// (`typing.Callable[...]` is `collections.abc.Callable[...]`). +fn is_abc_form(form: Marker) -> bool { + matches!( + form.0, + StaticStrings::Callable + | StaticStrings::Sequence + | StaticStrings::Mapping + | StaticStrings::Iterable + | StaticStrings::IteratorType + | StaticStrings::Generator + ) +} + +/// Owned clones of a tuple's items, preflighted like any container copy. +fn tuple_items(tuple: &Value, vm: &mut VM<'_>) -> RunResult { + let Some(HeapReadOutput::Tuple(items)) = tuple.read_heap(vm) else { + unreachable!("GenericAlias::args is always a tuple") + }; + let count = items.get(vm.heap).as_slice().len(); + vm.heap.tracker.check_allocation(count.saturating_mul(VALUE_SIZE))?; + Ok((0..count).map(|index| items.clone_item(index, vm)).collect()) +} + +/// CPython's `TypeError` for instantiating one of `collections.abc`'s classes. +fn abstract_class_error(name: &str, methods: &str) -> String { + let noun = if methods.contains(',') { "methods" } else { "method" }; + format!("Can't instantiate abstract class {name} without an implementation for abstract {noun} {methods}") +} + +/// Frozen helper for `typing.get_type_hints`: `alias_with(alias, args, include_extras)` +/// rebuilds `alias` around the resolved `args` tuple (the alias itself when they +/// are unchanged), and strips `Annotated[T, ...]` to `T` unless `include_extras`. +pub(crate) fn call_alias_with(args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let AliasWithArgs { + alias, + resolved, + include_extras, + } = AliasWithArgs::from_args(args, vm)?; + defer_drop!(alias, vm); + defer_drop!(resolved, vm); + let Some(HeapReadOutput::GenericAlias(generic)) = alias.read_heap(vm) else { + unreachable!("frozen code passes a generic alias") + }; + let (origin, args) = generic.parts(vm); + defer_drop!(args, vm); + if generic.get(vm.heap).is_annotated() { + let Some(HeapReadOutput::Tuple(resolved_items)) = resolved.read_heap(vm) else { + unreachable!("frozen code passes the resolved args as a tuple") + }; + let inner = resolved_items.clone_item(0, vm); + if !matches!(include_extras, Value::Bool(true)) { + return Ok(inner); + } + let Some(HeapReadOutput::Tuple(stored)) = args.read_heap(vm) else { + unreachable!("GenericAlias::args is always a tuple") + }; + defer_drop!(inner, vm); + let count = stored.get(vm.heap).as_slice().len(); + vm.heap.tracker.check_allocation(count.saturating_mul(VALUE_SIZE))?; + let mut items = smallvec![inner.clone_with_heap(vm)]; + for index in 1..count { + items.push(stored.clone_item(index, vm)); + } + let key = allocate_tuple(items, vm.heap); + return Ok(GenericAlias::allocate(origin, key, vm)); + } + if resolved.py_eq(args, vm)? { + Ok(alias.clone_with_heap(vm)) + } else { + Ok(GenericAlias::allocate(origin, resolved.clone_with_heap(vm), vm)) + } +} + +/// Arguments of the private `alias_with` helper. +#[derive(FromArgs)] +#[from_args(name = "alias_with")] +struct AliasWithArgs { + #[from_args(pos_only)] + alias: Value, + #[from_args(pos_only)] + resolved: Value, + #[from_args(pos_only)] + include_extras: Value, +} + /// Writes one `__args__` item the way CPython's `ga_repr_item` does: a type /// by its qualified name (`int`, `collections.deque`, a class's bare name), /// `...` for `Ellipsis`, and the ordinary repr for anything else. @@ -263,7 +873,7 @@ pub(crate) fn repr_type_arg( ) -> RunResult<()> { match item { Value::Ellipsis => Ok(f.write_str("...")?), - Value::Builtin(Builtins::Type(ty)) => Ok(f.write_str(&ty.name(vm.heap, vm.interns))?), + Value::Builtin(Builtins::Type(ty)) => Ok(f.write_str(&Type::from(*ty).name(vm.heap, vm.interns))?), Value::Builtin(Builtins::ExcType(exc_type)) => Ok(f.write_str(exc_type.into())?), Value::Builtin(Builtins::Function(BuiltinsFunctions::Type)) => Ok(f.write_str("type")?), Value::Ref(id) => match vm.heap.get(*id) { @@ -275,3 +885,60 @@ pub(crate) fn repr_type_arg( _ => item.py_repr_fmt(f, vm, heap_ids), } } + +/// Writes a list argument (`Callable[[int], str]`) element by element, each as +/// [`repr_type_arg`] writes it; `false` when `item` is not a list. As CPython's +/// `ga_repr` only looks inside a top-level list, a list nested deeper takes its +/// ordinary repr, whose cycle protection keeps a self-referential list finite. +fn repr_list_arg(item: &Value, f: &mut impl Write, vm: &mut VM<'_>, heap_ids: &mut LazyHeapSet) -> RunResult { + let Some(HeapReadOutput::List(list)) = item.read_heap(vm) else { + return Ok(false); + }; + f.write_char('[')?; + for index in 0..list.get(vm.heap).as_slice().len() { + if index > 0 { + if repr_should_truncate(index, vm)? { + f.write_str(", ...[timeout]")?; + break; + } + f.write_str(", ")?; + } + let element = list.clone_item(index, vm); + defer_drop!(element, vm); + repr_type_arg(element, f, vm, heap_ids)?; + } + f.write_char(']')?; + Ok(true) +} + +#[cfg(test)] +mod tests { + use serde::Serialize; + + use super::*; + + #[test] + fn legacy_origin_dump_loads_unchanged() { + #[derive(Serialize)] + struct LegacyAlias { + origin: Type, + args: Value, + } + + // Include a type after Instance, where the two enums' indices differ. + for origin in [Type::List, Type::ItertoolsChain] { + let legacy = LegacyAlias { + origin, + args: Value::None, + }; + let bytes = minicbor_serde::to_vec(&legacy).unwrap(); + let alias: GenericAlias = minicbor_serde::from_slice(&bytes).unwrap(); + + assert_eq!( + alias.origin, + AliasOrigin::Builtin(BuiltinType::try_from(origin).unwrap()) + ); + assert_eq!(minicbor_serde::to_vec(&alias).unwrap(), bytes); + } + } +} diff --git a/crates/bashkit-monty/src/types/hash_table.rs b/crates/bashkit-monty/src/types/hash_table.rs index c0066b652..d19e20bd3 100644 --- a/crates/bashkit-monty/src/types/hash_table.rs +++ b/crates/bashkit-monty/src/types/hash_table.rs @@ -201,8 +201,8 @@ impl PyHashTable { /// Overwrites the entry a probe found, returning the old one. /// /// The replacement must probe the same as what it displaces, since its - /// bucket stays where it is. A dict rewriting the value at an existing key - /// is the intended use. + /// bucket stays where it is. A cache storing a new result for an existing + /// key is the intended use. #[inline] #[expect(clippy::needless_pass_by_value, reason = "taking the slot spends it")] pub(crate) fn replace(&mut self, slot: Slot, entry: E) -> E { @@ -219,6 +219,19 @@ impl PyHashTable { mem::replace(old, entry) } + /// The entry a probe found, for rewriting in place. + /// + /// The entry must keep probing the same, since its bucket stays where it + /// is. A dict rebinding the value at an existing key is the intended use. + #[inline] + #[expect(clippy::needless_pass_by_value, reason = "taking the slot spends it")] + pub(crate) fn entry_mut(&mut self, slot: Slot) -> &mut E { + self.entries + .get_mut(slot.0) + .filter(|e| e.is_live()) + .expect(PROBE_SLOT_LIVE) + } + /// Removes the entry a probe found, returning it. #[inline] #[expect(clippy::needless_pass_by_value, reason = "taking the slot spends it")] diff --git a/crates/bashkit-monty/src/types/hashlib/mod.rs b/crates/bashkit-monty/src/types/hashlib/mod.rs index d3611edbc..4c1c7c692 100644 --- a/crates/bashkit-monty/src/types/hashlib/mod.rs +++ b/crates/bashkit-monty/src/types/hashlib/mod.rs @@ -38,6 +38,7 @@ use crate::{ hash::{HashValue, identity_hash}, heap::{DropWithContext, Heap, HeapData, HeapId, HeapItem, HeapObjectRead, HeapRead}, intern::StaticStrings, + py_value::PyValue, types::{LazyHeapSet, PyTrait, Type, allocate_string, bytes::allocate_bytes, py_trait::PyObjectIdentity}, value::{EitherStr, Value}, }; @@ -513,10 +514,11 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, HashObject> { } let data = args.get_one_arg(&method("update"), vm.heap)?; defer_drop!(data, vm); + let data = data.py_value(vm); // The input borrows the heap, so the state is lifted out while // it is absorbed and put back on every path. let mut hash = mem::take(self.get_mut(vm.heap)); - let absorbed = hash_input(data, vm).and_then(|input| hash.update(input, &vm.heap.tracker)); + let absorbed = hash_input(&data, vm).and_then(|input| hash.update(input, &vm.heap.tracker)); *self.get_mut(vm.heap) = hash; absorbed.map(|()| CallResult::Value(Value::None)) } @@ -579,15 +581,10 @@ fn xof_length(length: u64, bytes_per_output: usize, vm: &VM<'_>) -> RunResult(value: &'a Value, vm: &'a VM<'_>) -> RunResult<&'a [u8]> { +pub(crate) fn hash_input<'a, 'h>(value: &'a PyValue<'h>, vm: &'a VM<'h>) -> RunResult<&'a [u8]> { match value { - Value::InternBytes(id) => Ok(vm.interns.get_bytes(*id)), - Value::Ref(id) => match vm.heap.get(*id) { - HeapData::Bytes(bytes) => Ok(bytes.as_slice()), - HeapData::Str(_) => Err(ExcType::type_error("Strings must be encoded before hashing")), - _ => Err(ExcType::type_error("object supporting the buffer API required")), - }, - Value::InternString(_) => Err(ExcType::type_error("Strings must be encoded before hashing")), + PyValue::Str(_) => Err(ExcType::type_error("Strings must be encoded before hashing")), + PyValue::Bytes(bytes) => Ok(bytes.as_slice(vm)), _ => Err(ExcType::type_error("object supporting the buffer API required")), } } diff --git a/crates/bashkit-monty/src/types/host_class.rs b/crates/bashkit-monty/src/types/host_class.rs index e3c812ddd..100178d7c 100644 --- a/crates/bashkit-monty/src/types/host_class.rs +++ b/crates/bashkit-monty/src/types/host_class.rs @@ -7,7 +7,7 @@ use std::{ use monty_types::{MontyUuid, unstable::ClassTypeNode}; -use super::{Dict, LazyHeapSet, PyTrait, attribute_name_value, str::allocate_string}; +use super::{Dict, LazyHeapSet, PyTrait, list::repr_should_truncate, str::allocate_string}; use crate::{ args::ArgValues, bytecode::{CallResult, VM}, @@ -150,7 +150,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, HostClass> { fn py_set_attr(&mut self, name: &EitherStr, value: Value, vm: &mut VM<'h>) -> RunResult<()> { let mut value_guard = DropGuard::new(value, vm); - let name = attribute_name_value(name, value_guard.ctx()); + let name = name.as_value(value_guard.ctx().heap); let (value, vm) = value_guard.into_parts(); let old_value = self.set_attr(name, value, vm)?; old_value.drop_with(vm); @@ -193,12 +193,12 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, HostClass> { defer_drop!(key, vm); // Keys are strings in practice; render a non-string key (possible // in host-built attrs) via repr rather than fail. - let key_str = if let Ok(s) = key.to_str(vm) { + let key_str = if let Some(s) = key.as_str(vm) { s.to_owned() } else { let repr = key.py_repr(vm)?; defer_drop!(repr, vm); - repr.to_str(vm)?.to_owned() + repr.as_str(vm).expect("py_repr returns str").to_owned() }; // The value is cloned only after the fallible key formatting, so a // formatting error cannot strand an unguarded clone; re-reading at @@ -314,8 +314,12 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, HostClass> { /// /// Each caller supplies its own field list via `field`, mapping an index to that /// field's name and a cloned value (dropped here). A cycle renders `...`, a -/// `None` value ``, a memory limit truncates `...[timeout]`, and a time -/// limit raises (bashkit fork: see `repr_check_time`). +/// `None` value ``, and exhausting a memory limit truncates `...[timeout]`. +// bashkit fork: a time limit raises here rather than truncating, the inverse +// of upstream; the call site is unchanged, the semantics live in +// [`repr_should_truncate`]. A shared `D(d, d)` graph otherwise kept +// formatting: with the tracker-wide cadence only one call in 64 sees the +// expired clock, so truncation never unwound the walk. /// /// `field` is resolved immediately before that field is written, never all up /// front, so a `__repr__` that mutates a later field is observed — matching the @@ -338,11 +342,7 @@ pub(crate) fn write_dataclass_repr<'h>( if i > 0 { // Same between-item checkpoint as sequence repr, so a wide instance // cannot outrun its time limit. - // bashkit fork: through `repr_check_time`, so a time hit errors - // instead of truncating (a shared `D(d, d)` graph otherwise kept - // formatting: with the tracker-wide cadence only one call in 64 - // sees the expired clock, so truncation never unwound the walk). - if super::list::repr_check_time(i, vm)? { + if repr_should_truncate(i, vm)? { f.write_str(", ...[timeout]")?; break; } diff --git a/crates/bashkit-monty/src/types/inline_str.rs b/crates/bashkit-monty/src/types/inline_str.rs new file mode 100644 index 000000000..aa0d241f0 --- /dev/null +++ b/crates/bashkit-monty/src/types/inline_str.rs @@ -0,0 +1,156 @@ +//! Fixed-capacity UTF-8 strings shared by values, views and iterators. + +use std::str; + +use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error}; + +use crate::{bytecode::VM, heap::HeapData, value::Value}; + +/// UTF-8 text of at most 15 bytes. +/// The length enum supplies niches so a containing `Value` remains 16 bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) struct InlineStr { + len: InlineLen, + bytes: [u8; 15], +} + +impl InlineStr { + pub(crate) fn new(text: &str) -> Option { + let len = InlineLen::from_len(text.len())?; + let mut bytes = [0; 15]; + bytes[..text.len()].copy_from_slice(text.as_bytes()); + Some(Self { len, bytes }) + } + + /// Compares without validating UTF-8; non-string operands return `None`. + pub(crate) fn eq_value(&self, other: &Value, vm: &VM<'_>) -> Option { + match other { + Value::InlineString(other) => Some(self == other), + Value::InternString(id) => Some(self.as_bytes() == vm.interns.get_str(*id).as_bytes()), + Value::Ref(id) if let HeapData::Str(other) = vm.heap.get(*id) => { + Some(self.as_bytes() == other.as_str().as_bytes()) + } + _ => None, + } + } + + pub(crate) fn as_bytes(&self) -> &[u8] { + &self.bytes[..self.len.get()] + } + + pub(crate) fn as_str(&self) -> &str { + str::from_utf8(self.as_bytes()).expect("inline string contains valid UTF-8") + } +} + +impl Serialize for InlineStr { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for InlineStr { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + Self::new(&text).ok_or_else(|| D::Error::custom("inline string exceeds capacity")) + } +} + +/// Byte length for an inline UTF-8 string. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +enum InlineLen { + L0, + L1, + L2, + L3, + L4, + L5, + L6, + L7, + L8, + L9, + L10, + L11, + L12, + L13, + L14, + L15, +} + +impl InlineLen { + fn from_len(len: usize) -> Option { + Some(match len { + 0 => Self::L0, + 1 => Self::L1, + 2 => Self::L2, + 3 => Self::L3, + 4 => Self::L4, + 5 => Self::L5, + 6 => Self::L6, + 7 => Self::L7, + 8 => Self::L8, + 9 => Self::L9, + 10 => Self::L10, + 11 => Self::L11, + 12 => Self::L12, + 13 => Self::L13, + 14 => Self::L14, + 15 => Self::L15, + _ => return None, + }) + } + + fn get(self) -> usize { + self as usize + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{types::StringIterator, value::Value}; + + #[test] + fn capacity_counts_utf8_bytes() { + assert_eq!(size_of::(), 16); + assert_eq!(size_of::(), 16); + for text in ["", "a", "é", "abcdefghijklmno", "éééééééa"] { + assert_eq!(InlineStr::new(text).unwrap().as_str(), text); + } + assert!(InlineStr::new("abcdefghijklmnop").is_none()); + assert!(InlineStr::new("éééééééé").is_none()); + } + + #[test] + fn values_serialize_as_text() { + for length in 0..=15 { + let text = "x".repeat(length); + let value = Value::InlineString(InlineStr::new(&text).unwrap()); + let expected = format!(r#"{{"S":"{text}"}}"#); + assert_eq!(serde_json::to_string(&value).unwrap(), expected); + let encoded = minicbor_serde::to_vec(&value).unwrap(); + let restored: Value = minicbor_serde::from_slice(&encoded).unwrap(); + assert_eq!(restored.inline_str(), Some(text.as_str())); + } + } + + #[test] + fn deserialization_requires_a_short_string() { + let long = minicbor_serde::to_vec("x".repeat(16)).unwrap(); + assert!(minicbor_serde::from_slice::(&long).is_err()); + let wrong_type = minicbor_serde::to_vec(42).unwrap(); + assert!(minicbor_serde::from_slice::(&wrong_type).is_err()); + } + + #[test] + fn iterator_roundtrip_preserves_its_position() { + let stored = serde_json::json!({ + "source": {"Inline": "aé"}, "byte_offset": 1, "ascii": false, + }); + let iterator: StringIterator = serde_json::from_value(stored.clone()).unwrap(); + let encoded = minicbor_serde::to_vec(&iterator).unwrap(); + let restored: StringIterator = minicbor_serde::from_slice(&encoded).unwrap(); + assert_eq!(serde_json::to_value(restored).unwrap(), stored); + } +} diff --git a/crates/bashkit-monty/src/types/instance.rs b/crates/bashkit-monty/src/types/instance.rs index 80358df72..fac418745 100644 --- a/crates/bashkit-monty/src/types/instance.rs +++ b/crates/bashkit-monty/src/types/instance.rs @@ -2,7 +2,7 @@ use std::{borrow::Cow, fmt::Write}; use monty_types::MontyUuid; -use super::{Dict, LazyHeapSet, PyTrait, Type, attribute_name_value}; +use super::{Dict, LazyHeapSet, PyTrait, Type}; use crate::{ args::{ArgValues, KwargsValues}, boundary_uuid::create_uuid, @@ -362,7 +362,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Instance> { fn py_set_attr(&mut self, name: &EitherStr, value: Value, vm: &mut VM<'h>) -> RunResult<()> { let mut value_guard = DropGuard::new(value, vm); - let name = attribute_name_value(name, value_guard.ctx()); + let name = name.as_value(value_guard.ctx().heap); let (value, vm) = value_guard.into_parts(); let old_value = self.set_attr(name, value, vm)?; old_value.drop_with(vm); @@ -407,7 +407,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Instance> { dataclasses::dataclass_repr_fmt(self_id, &field_names, f, vm, heap_ids) } else if let Some(s) = instance_call_str_dunder(self_id, "__repr__", vm)? { defer_drop!(s, vm); - Ok(f.write_str(s.to_str(vm)?)?) + Ok(f.write_str(s.as_str(vm).expect("__repr__ result is validated"))?) } else { self.py_default_repr_fmt(f, vm) } @@ -610,6 +610,27 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, BoundMethod> { fn py_repr_fmt(&self, f: &mut impl Write, _vm: &mut VM<'h>, _heap_ids: &mut LazyHeapSet) -> RunResult<()> { Ok(write!(f, "")?) } + + /// `obj.method.__annotations__` and `__annotate__` are the function's, as + /// CPython's method type forwards them. + fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> RunResult> { + if !matches!(attr.as_str(vm.interns), "__annotations__" | "__annotate__") { + return Ok(None); + } + let func = self.get(vm.heap).func.clone_with_heap(vm); + defer_drop!(func, vm); + func.py_getattr(attr, vm).map(Some) + } + + fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult { + if !matches!(attr.as_str(vm.interns), "__annotations__" | "__annotate__") { + args.drop_with(vm); + return Err(ExcType::attribute_error("function", attr.as_str(vm.interns))); + } + let func = self.get(vm.heap).func.clone_with_heap(vm); + defer_drop!(func, vm); + func.py_value(vm).py_call_attr(vm, attr, args) + } } impl HeapItem for BoundMethod { @@ -976,10 +997,7 @@ fn class_member(class_id: HeapId, name: &str, vm: &VM<'_>) -> Option { /// programmer-error tripwire. pub(crate) fn class_name<'i>(class_id: HeapId, heap: &Heap, interns: &'i Interns) -> Cow<'i, str> { match heap.get(class_id) { - HeapData::Class(class) => match class.name() { - EitherStr::Interned(id) => Cow::Borrowed(interns.get_str(*id)), - EitherStr::Heap(s) => Cow::Owned(s.clone()), - }, + HeapData::Class(class) => class.name().to_cow(interns), _ => unreachable!("class_name called with a non-class heap id"), } } @@ -1051,3 +1069,53 @@ impl<'h> PyDeepCopy<'h> for HeapRead<'h, BoundMethod> { Ok(self.allocate_like(copied?, vm)) } } + +#[cfg(test)] +mod tests { + use std::fmt; + + use monty_types::{CompileOptions, PrintWriter, ResourceTracker}; + + use super::*; + use crate::{bytecode::FrameExit, heap::HeapReader, run::Executor}; + + struct FailingWriter; + + impl Write for FailingWriter { + fn write_str(&mut self, _text: &str) -> fmt::Result { + Err(fmt::Error) + } + } + + #[test] + fn user_repr_propagates_writer_errors() { + let mut executor = Executor::new( + "class Example:\n def __repr__(self):\n return 'result'\nExample()".to_owned(), + "test.py", + Vec::new(), + CompileOptions::default(), + ) + .unwrap(); + let mut heap = Heap::new(16, ResourceTracker::default()); + let globals = executor.empty_globals(); + + HeapReader::with(&mut heap, &mut executor, |reader, executor| { + let vm = &mut VM::new( + globals, + &mut executor.tables, + &executor.program, + reader, + PrintWriter::Disabled, + ); + let FrameExit::Return(value) = vm.run_external().unwrap() else { + unreachable!("the program returns its instance") + }; + defer_drop!(value, vm); + assert!( + value + .py_repr_fmt(&mut FailingWriter, vm, &mut LazyHeapSet::default()) + .is_err() + ); + }); + } +} diff --git a/crates/bashkit-monty/src/types/list.rs b/crates/bashkit-monty/src/types/list.rs index ce67c195c..3f11ca6ac 100644 --- a/crates/bashkit-monty/src/types/list.rs +++ b/crates/bashkit-monty/src/types/list.rs @@ -1,6 +1,6 @@ use std::{cmp::Ordering, fmt::Write, mem}; -use monty_types::ResourceError; // bashkit fork: a repr time hit returns this error +use monty_types::ResourceError; use serde::{Deserialize, Serialize}; use smallvec::SmallVec; @@ -20,11 +20,10 @@ use crate::{ intern::StaticStrings, modules::copy::{Memo, PyDeepCopy, deep_copy}, py_value::PyValue, - resource_checks::{check_repeat_size, check_value_buffer_growth}, + resource_checks::{check_repeat_size, check_value_buffer_growth, repeated_len, try_vec_with_capacity}, sorting::parse_and_sort, types::{ LazyHeapSet, Type, - long_int::repeat_count, slice::{normalize_sequence_index, slice_collect_iterator, value_to_i64_bound}, }, value::{EitherStr, VALUE_SIZE, Value}, @@ -643,47 +642,80 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, List> { let Some(HeapReadOutput::List(other)) = other.read_heap(vm) else { return Ok(None); }; - let mut items = self.clone_all_items(vm)?; - items.extend(other.clone_all_items(vm)?); + // The guard releases our clones if cloning `other` hits the memory limit. + let mut items = DropGuard::new(self.clone_all_items(vm)?, vm); + let (left, vm) = items.as_parts_mut(); + left.extend(other.clone_all_items(vm)?); + let (items, vm) = items.into_parts(); let id = vm.heap.allocate(HeapData::List(List::new(items))); Ok(Some(Value::Ref(id))) } fn py_mul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { - let Some(count) = repeat_count(other, vm)? else { + let Some(count) = other.py_value(vm).repeat_count(vm)? else { return Ok(None); }; - let value = self.get(vm.heap); - check_repeat_size(value.len().saturating_mul(VALUE_SIZE), count, &vm.heap.tracker)?; - let mut result = Vec::with_capacity(value.len() * count); + let len = self.get(vm.heap).len(); + let total = repeated_len(len, count, VALUE_SIZE)?; + check_repeat_size(len.saturating_mul(VALUE_SIZE), count, &vm.heap.tracker)?; + // The guard releases the clones built so far if the time poll trips. + let mut result = DropGuard::new(try_vec_with_capacity(total)?, vm); for rep in 0..count { - result.extend(value.as_slice().iter().map(|value| value.clone_with_heap(vm.heap))); + let (items, vm) = result.as_parts_mut(); + items.extend( + self.get(vm.heap) + .as_slice() + .iter() + .map(|value| value.clone_with_heap(vm.heap)), + ); vm.heap.tracker.check_time_every(rep)?; } - Ok(Some(Value::Ref(vm.heap.allocate(HeapData::List(List::new(result)))))) + let (items, vm) = result.into_parts(); + Ok(Some(Value::Ref(vm.heap.allocate(HeapData::List(List::new(items)))))) } fn py_rmul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { self.py_mul_impl(other, vm) } + /// Extends in place from a list or synchronous iterable, preserving aliases. fn py_iadd_impl(&mut self, other: &Value, vm: &mut VM<'h>) -> RunResult { - let Value::Ref(other_id) = other else { - return Ok(false); + // Lists use bulk copying; other operands follow the iterator protocol, including its errors. + let other_id = other + .ref_id() + .filter(|id| matches!(vm.heap.get(*id), HeapData::List(_))); + let Some(other_id) = other_id else { + // Append as the source yields so an iterator error keeps earlier additions. + let iterator = other.py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(iterator, vm); + let mut iterator = iterator.read(vm); + + // Preflight the size hint; append still checks growth if the iterator yields more. + let hint = iterator.iter_size_hint(vm); + vm.heap.tracker.check_allocation(hint.saturating_mul(VALUE_SIZE))?; + + while let Some(item) = iterator.py_next(vm)? { + self.append(vm, item)?; + } + return Ok(true); }; - if *other_id == self.id() { - // Self-extend: clone our own items with proper refcounting. Checked - // at 2× — the temporary clone plus the equal-sized target growth — - // up front, while no owned values need releasing on failure. + if other_id == self.id() { + // Snapshot before extending so `a += a` copies only the original items. + // Budget for both the snapshot and target growth before acquiring owned references. let len = self.get(vm.heap).items.len(); vm.heap.tracker.check_allocation(len.saturating_mul(2 * VALUE_SIZE))?; + self.get_mut(vm.heap) + .items + .try_reserve_exact(len) + .map_err(|_| ExcType::allocation_too_large())?; let items = self.clone_all_items(vm)?; + // Duplicating existing elements cannot change whether this list contains heap references. self.get_mut(vm.heap).items.extend(items); } else { // Read source list via HeapRead, clone items into a temporary Vec. // Checked at 2× — the clone plus the target growth — see above. - let source = vm.heap.read(*other_id); + let source = vm.heap.read(other_id); let HeapReadOutput::List(source_list) = source else { return Ok(false); }; @@ -691,8 +723,13 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, List> { vm.heap .tracker .check_allocation(source_len.saturating_mul(2 * VALUE_SIZE))?; + // Exact reservation avoids doubling a full list for a small source. + self.get_mut(vm.heap) + .items + .try_reserve_exact(source_len) + .map_err(|_| ExcType::allocation_too_large())?; let source_items = source_list.clone_all_items(vm)?; - // Check if new items contain refs + // GC skips lists without heap references; newly appended references must enable scanning. let has_new_refs = source_items.iter().any(|v| matches!(v, Value::Ref(_))); self.get_mut(vm.heap).items.extend(source_items); if has_new_refs { @@ -703,6 +740,46 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, List> { Ok(true) } + /// Repeats for integer or `__index__` counts, retaining identity and shared elements. + fn py_imul_impl(&mut self, other: &Value, vm: &mut VM<'h>) -> RunResult { + let Some(count) = other.py_value(vm).repeat_count(vm)? else { + return Ok(false); + }; + + // `__index__` can resize this list; read its length only after conversion. + let len = self.get(vm.heap).items.len(); + // These no-op repetitions need neither allocation nor reference-count changes. + if count == 1 || len == 0 { + return Ok(true); + } + + // Clear the existing list rather than replacing it, so aliases also see an empty list. + // Detach the items before releasing their references, which may include the list itself. + if count == 0 { + let items = mem::take(&mut self.get_mut(vm.heap).items); + self.get_mut(vm.heap).contains_refs = false; + items.drop_with(vm); + return Ok(true); + } + + // Check and reserve the entire result before appending, so allocation failure leaves it unchanged. + check_repeat_size(len.saturating_mul(VALUE_SIZE), count, &vm.heap.tracker)?; + let total = len.checked_mul(count).ok_or_else(ExcType::allocation_too_large)?; + self.get_mut(vm.heap) + .items + .try_reserve_exact(total - len) + .map_err(|_| ExcType::allocation_too_large())?; + + // Grow from the original prefix without a snapshot; only the vector's storage may move. + // Cloning preserves element identity; `contains_refs` stays valid because every element is already present. + for index in len..total { + let item = self.get(vm.heap).items[index % len].clone_with_heap(vm.heap); + self.get_mut(vm.heap).items.push(item); + vm.heap.tracker.check_time_every(index)?; + } + Ok(true) + } + /// Delegates methods to `call_list_method`. fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult { if attr.static_string(vm.interns) == Some(StaticStrings::Sort) { @@ -1062,14 +1139,13 @@ pub(crate) fn repr_sequence_fmt<'h>( f.write_char(start)?; // The item is fetched before the separator is written so nothing is emitted - // for an index that turned out to be out of range. `repr_check_time` bounds + // for an index that turned out to be out of range. `repr_should_truncate` bounds // reprs that keep growing the sequence from inside a user `__repr__`. for i in 0.. { let Some(item) = get_item(vm.heap, i) else { break }; defer_drop!(item, vm); if i > 0 { - // bashkit fork: `?` so a time hit errors instead of truncating (see `repr_check_time`). - if repr_check_time(i, vm)? { + if repr_should_truncate(i, vm)? { f.write_str(", ...[timeout]")?; break; } @@ -1097,8 +1173,7 @@ pub(crate) fn repr_items_fmt( ) -> RunResult<()> { for (i, item) in items.iter().enumerate() { if i > 0 { - // bashkit fork: `?` so a time hit errors instead of truncating (see `repr_check_time`). - if repr_check_time(i, vm)? { + if repr_should_truncate(i, vm)? { f.write_str(", ...[timeout]")?; break; } @@ -1109,26 +1184,32 @@ pub(crate) fn repr_items_fmt( Ok(()) } -/// Polls the time/memory soft limits every 64th item rather than every item, -/// keeping per-item overhead to one branch while still truncating huge reprs -/// promptly with `", ...[timeout]"`. Pinned by bashkit's +/// Polls the time and memory soft limits every 64th item of a container repr. +/// +/// `Ok(true)` means the repr should be truncated with `", ...[timeout]"`. +/// Pinned by bashkit's /// `python_security_tests::whitebox_resource_limits::shared_graph_walks_respect_time_limit`. /// /// bashkit fork: two changes, both for reprs of shared graphs (`x = [x, x]` -/// thirty times is 2^30 nested two-item lists). -/// - The poll cadence is tracker-wide (see `check_time_every`), not the -/// index `i` within one container: a two-item list never reached index 63, -/// so the clock was never read and the repr ran for minutes past the limit -/// on a thread the host cannot interrupt. -/// - A time-limit hit is returned as an error instead of truncating. The -/// time budget never recovers within a run, and truncating only ends the -/// current container while every enclosing one keeps formatting its next -/// item, and with the tracker-wide cadence only one call in 64 sees the -/// expired clock, so the others would keep formatting. A memory hit still -/// truncates, as upstream does. Every repr checkpoint goes through here. -pub(crate) fn repr_check_time(_i: usize, vm: &VM<'_>) -> RunResult { +/// thirty times is 2^30 nested two-item lists). Upstream's own call sites are +/// kept verbatim; the divergence lives here, in the one helper every repr +/// checkpoint goes through. +/// - The poll cadence is tracker-wide (see `check_time_every`), not the index +/// `i` within one container, so `i` is ignored: a two-item list never +/// reached index 63, so the clock was never read and the repr ran for +/// minutes past the limit on a thread the host cannot interrupt. +/// - A time-limit hit is returned as an error instead of truncating (upstream +/// truncates on time and propagates memory errors; the fork inverts both +/// arms). The time budget never recovers within a run, and truncating only +/// ends the current container while every enclosing one keeps formatting +/// its next item -- and with the tracker-wide cadence only one call in 64 +/// sees the expired clock, so the others would keep formatting. A memory +/// hit truncates instead. +pub(crate) fn repr_should_truncate(_i: usize, vm: &VM<'_>) -> RunResult { match vm.heap.tracker.check_memory_time_every(0) { Ok(()) => Ok(false), + // bashkit fork: both arms are the inverse of upstream's -- a time hit + // raises, a memory hit truncates. See this function's doc comment. Err(err @ ResourceError::Time { .. }) => Err(err.into()), Err(_) => Ok(true), } diff --git a/crates/bashkit-monty/src/types/long_int.rs b/crates/bashkit-monty/src/types/long_int.rs index 913fa329b..0244fb20e 100644 --- a/crates/bashkit-monty/src/types/long_int.rs +++ b/crates/bashkit-monty/src/types/long_int.rs @@ -32,7 +32,6 @@ use crate::{ heap::{Heap, HeapData, HeapObjectRead}, identity::Identity, intern::LongIntId, - py_value::PyValue, resource_checks::{check_div_size, check_lshift_size, check_mult_size, check_pow_size}, types::{ LazyHeapSet, PyTrait, Type, @@ -172,16 +171,6 @@ impl<'h> PyInt<'h> { ) } - /// Resolves a sequence repetition count, treating negatives as zero. - pub(crate) fn repeat_count(&self, vm: &VM<'h>) -> RunResult { - self.with_value( - vm, - |value| usize::try_from(value.max(0)).ok(), - |value| if value.is_negative() { Some(0) } else { value.to_usize() }, - ) - .ok_or_else(|| ExcType::overflow_index_sized_int().into()) - } - /// Runs size-specific integer operations without materializing or cloning a BigInt. pub(crate) fn with_value(&self, vm: &VM<'h>, small: impl FnOnce(i64) -> R, big: impl FnOnce(&BigInt) -> R) -> R { match self { @@ -638,15 +627,6 @@ impl LongInt { } } -/// Extracts a Python integer as a sequence repetition count. -pub(crate) fn repeat_count(value: &Value, vm: &VM<'_>) -> RunResult> { - match value.py_value(vm) { - PyValue::Int(value) => value.repeat_count(vm).map(Some), - PyValue::Bool(value) => Ok(Some(usize::from(value))), - _ => Ok(None), - } -} - /// Compares a `BigInt` against an `f64` *exactly*, matching CPython's mixed /// `int`/`float` comparison with no precision loss in either direction /// (neither operand is rounded to the other's type). diff --git a/crates/bashkit-monty/src/types/lru_cache.rs b/crates/bashkit-monty/src/types/lru_cache.rs index 557f2c281..4d532c64d 100644 --- a/crates/bashkit-monty/src/types/lru_cache.rs +++ b/crates/bashkit-monty/src/types/lru_cache.rs @@ -76,6 +76,11 @@ impl LruCache { } } + /// The wrapped callable (`__wrapped__`), or `None` for a decorator awaiting one. + pub(crate) fn wrapped(&self) -> Option<&Value> { + self.func.as_ref() + } + /// Invokes `on_child` for each heap id this wrapper owns (GC trace hook). /// /// MUST report exactly the ids [`HeapItem::py_dec_ref_ids`] releases. diff --git a/crates/bashkit-monty/src/types/mod.rs b/crates/bashkit-monty/src/types/mod.rs index 7ce64cb2e..de6363e51 100644 --- a/crates/bashkit-monty/src/types/mod.rs +++ b/crates/bashkit-monty/src/types/mod.rs @@ -1,3 +1,4 @@ +mod builtin_type; /// Type definitions for Python runtime values. /// /// This module contains structured types that wrap heap-allocated data @@ -19,10 +20,12 @@ pub mod dict_view; pub mod dir_scan; pub mod ext_function; pub mod file; +pub mod forward_ref; pub mod generic_alias; pub mod hash_table; pub mod hashlib; pub mod host_class; +pub(crate) mod inline_str; pub mod instance; pub mod iter; pub mod itertools; @@ -40,6 +43,7 @@ pub mod random; pub mod range; pub mod re_match; pub mod re_pattern; +mod re_syntax; pub mod set; pub mod slice; pub mod str; @@ -52,6 +56,7 @@ mod unicode_type; mod unicode_type_data; pub mod union; +pub(crate) use builtin_type::BuiltinType; pub(crate) use bytes::{Bytes, BytesIterator}; pub(crate) use class::Class; pub(crate) use complex::Complex; @@ -62,6 +67,7 @@ pub(crate) use dict_view::{DictItemsView, DictKeysView, DictValuesView}; pub(crate) use dir_scan::DirScan; pub(crate) use ext_function::ExtFunction; pub(crate) use file::OpenFile; +pub(crate) use forward_ref::ForwardRef; pub(crate) use generic_alias::GenericAlias; pub(crate) use hashlib::HashObject; pub(crate) use host_class::{HostClass, HostClassType, host_class_type}; @@ -76,7 +82,7 @@ pub(crate) use namedtuple::{NamedTuple, NamedTupleClass}; pub(crate) use partial::Partial; pub(crate) use path::Path; pub(crate) use property::Property; -pub(crate) use py_trait::{CmpOrder, LazyHeapSet, PyTrait, attribute_name_value}; +pub(crate) use py_trait::{CmpOrder, LazyHeapSet, PyTrait}; pub(crate) use random::{Random, SessionRandom}; pub(crate) use range::{Range, RangeIterator}; pub(crate) use re_match::ReMatch; diff --git a/crates/bashkit-monty/src/types/module.rs b/crates/bashkit-monty/src/types/module.rs index ae3af26e8..e4359ce03 100644 --- a/crates/bashkit-monty/src/types/module.rs +++ b/crates/bashkit-monty/src/types/module.rs @@ -1,13 +1,13 @@ //! Python module type for representing imported modules. -use monty_types::MontyUuid; +use monty_types::{MontyUuid, StringRepr}; use crate::{ args::ArgValues, bytecode::{CallResult, VM}, defer_drop, - exception_private::{ExcType, ExcTypeExt, RunResult}, - heap::{DropGuard, HeapId, HeapItem, HeapRead}, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + heap::{DropGuard, DropWithContext, HeapData, HeapId, HeapItem, HeapRead, HeapReadOutput}, intern::{Interns, StaticStrings, StringId}, types::Dict, value::{EitherStr, Value}, @@ -19,6 +19,8 @@ use crate::{ /// and a dictionary of attributes. Bundled modules like `sys` and `typing` /// control their own attributes; a host module arrives over the boundary with /// its attrs and an [`id`](Self::id), which it carries back when exported. +/// A module imported from a `.py` file keeps its attributes in its +/// [`FileModule`] namespace instead, and leaves `attrs` empty. #[derive(Debug, serde::Serialize, serde::Deserialize)] pub(crate) struct Module { /// The module name (e.g., "sys", "typing"). @@ -29,16 +31,29 @@ pub(crate) struct Module { /// `None` for a bundled module. #[serde(default)] id: Option, + /// Set for a module imported from a `.py` file. + #[serde(default)] + file: Option, } -/// A module's name: interned for a bundled module, owned text for a host one, -/// since the VM cannot intern at runtime. Untagged so a bundled name still -/// dumps as the bare interned id it always has. +/// The parts of a module that only a `.py` file import has. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct FileModule { + /// The module's globals dict, OWNED. Its functions resolve their globals + /// through it, so attribute reads and writes go here and stay visible to them. + namespace: HeapId, + /// The virtual path the module was read from, for its repr. + origin: String, +} + +/// A module's name: interned for a bundled module, owned text for a host or +/// file one, since the VM cannot intern at runtime. Untagged so a bundled name +/// still dumps as the bare interned id it always has. #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub(crate) enum ModuleName { Interned(StringId), - Host(String), + Owned(String), } impl Module { @@ -50,15 +65,28 @@ impl Module { name: ModuleName::Interned(interns.intern_static(name)), attrs: Dict::new(), id: None, + file: None, } } /// Creates a host module from its wire name, identity and already-converted attrs. pub fn host(name: String, id: MontyUuid, attrs: Dict) -> Self { Self { - name: ModuleName::Host(name), + name: ModuleName::Owned(name), attrs, id: Some(id), + file: None, + } + } + + /// Creates a module imported from the file at `origin`, taking ownership of + /// the `namespace` dict reference its code runs in. + pub fn file(name: String, namespace: HeapId, origin: String) -> Self { + Self { + name: ModuleName::Owned(name), + attrs: Dict::new(), + id: None, + file: Some(FileModule { namespace, origin }), } } @@ -66,10 +94,30 @@ impl Module { pub fn name_str<'a>(&'a self, interns: &'a Interns) -> &'a str { match &self.name { ModuleName::Interned(id) => interns.get_str(*id), - ModuleName::Host(name) => name.as_str(), + ModuleName::Owned(name) => name.as_str(), + } + } + + /// ``, or `` for a file module, + /// both quoted as `repr()` quotes a string. + pub fn repr(&self, interns: &Interns) -> String { + let name = StringRepr(self.name_str(interns)); + match self.origin() { + Some(origin) => format!("", StringRepr(origin)), + None => format!(""), } } + /// A file module's namespace dict (borrowed); `None` for bundled and host modules. + pub fn namespace(&self) -> Option { + self.file.as_ref().map(|file| file.namespace) + } + + /// The virtual path a file module was read from. + pub fn origin(&self) -> Option<&str> { + self.file.as_ref().map(|file| file.origin.as_str()) + } + /// The host identity of the module; `None` for a bundled module. pub fn id(&self) -> Option { self.id @@ -93,14 +141,29 @@ impl Module { .expect("module attribute keys are interned, so hashing cannot fail"); } - /// Returns whether this module has any heap references in its attributes. - pub fn has_refs(&self) -> bool { - self.attrs.has_refs() + /// Calls `on_child` for every heap reference the module holds, for the cycle collector. + pub fn for_each_child_id(&self, mut on_child: impl FnMut(HeapId)) { + if let Some(namespace) = self.namespace() { + on_child(namespace); + } + if self.attrs.has_refs() { + for (k, v) in &self.attrs { + if let Value::Ref(id) = k { + on_child(*id); + } + if let Value::Ref(id) = v { + on_child(*id); + } + } + } } /// Collects child HeapIds for reference counting. pub fn py_dec_ref_ids(&mut self, stack: &mut Vec) { self.attrs.py_dec_ref_ids(stack); + if let Some(namespace) = self.namespace() { + stack.push(namespace); + } } } @@ -111,16 +174,12 @@ impl<'h> HeapRead<'h, Module> { /// For `Property` values, invokes the property getter rather than returning /// the Property itself - this implements Python's descriptor protocol. pub fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> Option { - let value = self - .get(vm.heap) - .attrs - .get_by_str(attr.as_str(vm.interns), vm.heap, vm.interns)?; - + let value = self.attr_value(attr.as_str(vm.interns), vm)?; // If the value is a Property, invoke its getter to compute the actual value - if let Value::Property(prop) = *value { + if let Value::Property(prop) = value { Some(prop.get()) } else { - Some(CallResult::Value(value.clone_with_heap(vm))) + Some(CallResult::Value(value)) } } @@ -135,19 +194,8 @@ impl<'h> HeapRead<'h, Module> { let mut args_guard = DropGuard::new(args, vm); let vm = args_guard.ctx(); - let attr_str = match attr { - EitherStr::Interned(id) => vm.interns.get_str(*id), - EitherStr::Heap(s) => { - return Err(ExcType::attribute_error_module( - self.get(vm.heap).name_str(vm.interns), - s, - )); - } - }; - - match self.get(vm.heap).attrs().get_by_str(attr_str, vm.heap, vm.interns) { + match self.attr_value(attr.as_str(vm.interns), vm) { Some(value) => { - let value = value.clone_with_heap(vm); let (args, vm) = args_guard.into_parts(); defer_drop!(value, vm); vm.call_function(value, args) @@ -158,10 +206,43 @@ impl<'h> HeapRead<'h, Module> { )), } } + + /// Binds an attribute on a file module's namespace, so the module's own + /// functions see it; other modules reject assignment. + pub fn py_set_attr(&self, name: &EitherStr, value: Value, vm: &mut VM<'h>) -> RunResult<()> { + let Some(namespace) = self.get(vm.heap).namespace() else { + value.drop_with(vm); + return Err(ExcType::attribute_error_no_setattr("module", name.as_str(vm.interns))); + }; + let key = name.as_value(vm.heap); + let HeapReadOutput::Dict(dict) = vm.heap.read(namespace) else { + key.drop_with(vm); + value.drop_with(vm); + return Err(RunError::internal("module namespace is not a dict")); + }; + let old = dict.set(key, value, vm)?; + old.drop_with(vm); + Ok(()) + } + + /// An owned copy of the attribute `name`, from the file namespace or `attrs`. + fn attr_value(&self, name: &str, vm: &VM<'h>) -> Option { + let module = self.get(vm.heap); + let attrs = match module.namespace() { + Some(namespace) => match vm.heap.get(namespace) { + HeapData::Dict(dict) => dict, + _ => return None, + }, + None => &module.attrs, + }; + attrs + .get_by_str(name, vm.heap, vm.interns) + .map(|value| value.clone_with_heap(vm.heap)) + } } impl HeapItem for Module { fn py_dec_ref_ids(&mut self, stack: &mut Vec) { - self.attrs.py_dec_ref_ids(stack); + Self::py_dec_ref_ids(self, stack); } } diff --git a/crates/bashkit-monty/src/types/namedtuple.rs b/crates/bashkit-monty/src/types/namedtuple.rs index 0b9a2578e..a67e05d04 100644 --- a/crates/bashkit-monty/src/types/namedtuple.rs +++ b/crates/bashkit-monty/src/types/namedtuple.rs @@ -35,14 +35,13 @@ use crate::{ defer_drop, defer_drop_mut, exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, hash::{HashValue, identity_hash}, - heap::{DropWithContext, HeapData, HeapId, HeapItem, HeapObjectRead, HeapRead, HeapReadOutput}, + heap::{DropGuard, DropWithContext, HeapData, HeapId, HeapItem, HeapObjectRead, HeapRead, HeapReadOutput}, intern::{Interns, StaticStrings}, modules::copy::{Memo, PyDeepCopy, deep_copy_slots}, - resource_checks::check_repeat_size, + resource_checks::{check_repeat_size, repeated_len}, types::{ Dict, Type, Union, allocate_tuple, iter::collect_owned_iterable, - long_int::repeat_count, py_trait::LazyHeapSet, slice::{normalize_sequence_index, slice_collect_iterator, value_to_i64_bound}, str::allocate_string, @@ -448,23 +447,31 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, NamedTuple> { /// `namedtuple * int` — repetition into a plain tuple, matching CPython's /// inherited `tuple.__mul__`. fn py_mul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { - let Some(count) = repeat_count(other, vm)? else { + let Some(count) = other.py_value(vm).repeat_count(vm)? else { return Ok(None); }; let len = self.get(vm.heap).len(); if count == 0 || len == 0 { return Ok(Some(vm.heap.get_empty_tuple())); } + let total = repeated_len(len, count, mem::size_of::())?; check_repeat_size(len.saturating_mul(mem::size_of::()), count, &vm.heap.tracker)?; - let mut result: TupleVec = SmallVec::with_capacity(len * count); + let mut items = TupleVec::new(); + items + .try_reserve_exact(total) + .map_err(|_| ExcType::allocation_too_large())?; + // The guard releases the clones built so far if the time poll trips. + let mut result = DropGuard::new(items, vm); for rep in 0..count { - for i in 0..len { - let item = self.get(vm.heap).as_vec()[i].clone_with_heap(vm.heap); - result.push(item); + let (items, vm) = result.as_parts_mut(); + // Pushes, not `extend`: its per-call reserve dominates when each pass adds one item. + for value in self.get(vm.heap).as_vec() { + items.push(value.clone_with_heap(vm.heap)); } vm.heap.tracker.check_time_every(rep)?; } - Ok(Some(allocate_tuple(result, vm.heap))) + let (items, vm) = result.into_parts(); + Ok(Some(allocate_tuple(items, vm.heap))) } fn py_rmul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { @@ -740,7 +747,7 @@ impl<'h> HeapRead<'h, NamedTuple> { let names = self.get(vm.heap).field_names.clone(); let mut pairs: Vec<(Value, Value)> = Vec::with_capacity(names.len()); for (i, name) in names.iter().enumerate() { - let key = field_name_value(name, vm); + let key = name.as_value(vm.heap); let value = self.get(vm.heap).items[i].clone_with_heap(vm.heap); pairs.push((key, value)); } @@ -964,7 +971,7 @@ impl<'h> HeapRead<'h, NamedTupleClass> { let start = n - n_defaults; let mut pairs: Vec<(Value, Value)> = Vec::with_capacity(n_defaults); for j in 0..n_defaults { - let key = field_name_value(&self.get(vm.heap).field_names[start + j].clone(), vm); + let key = self.get(vm.heap).field_names[start + j].as_value(vm.heap); let value = self.get(vm.heap).defaults[j].clone_with_heap(vm.heap); pairs.push((key, value)); } @@ -1277,18 +1284,10 @@ pub(crate) fn build_namedtuple( /// Builds a tuple `Value` of the given field names (as string values). fn fields_tuple_from(names: &[EitherStr], vm: &mut VM<'_>) -> Value { - let items: Vec = names.iter().map(|name| field_name_value(name, vm)).collect(); + let items: Vec = names.iter().map(|name| name.as_value(vm.heap)).collect(); allocate_tuple(SmallVec::from_vec(items), vm.heap) } -/// Converts an interned/heap field name into a string `Value`. -fn field_name_value(name: &EitherStr, vm: &mut VM<'_>) -> Value { - match name { - EitherStr::Interned(id) => Value::InternString(*id), - EitherStr::Heap(s) => allocate_string(s.clone(), vm.heap), - } -} - /// Normalizes call kwargs into `(name, value)` pairs, dropping non-interned /// keys' heap references. Non-string keys (only reachable via `**` unpacking) /// map to an empty name, which then surfaces as an unexpected-keyword error. diff --git a/crates/bashkit-monty/src/types/partial.rs b/crates/bashkit-monty/src/types/partial.rs index 57b83011d..a13eb399a 100644 --- a/crates/bashkit-monty/src/types/partial.rs +++ b/crates/bashkit-monty/src/types/partial.rs @@ -26,7 +26,7 @@ use crate::{ }, intern::StaticStrings, modules::copy::{Memo, PyDeepCopy, deep_copy, deep_copy_pair}, - types::{Dict, LazyHeapSet, PyTrait, Type, list::repr_check_time, tuple::allocate_tuple}, + types::{Dict, LazyHeapSet, PyTrait, Type, list::repr_should_truncate, tuple::allocate_tuple}, value::{EitherStr, VALUE_SIZE, Value}, }; @@ -230,7 +230,7 @@ fn merge_keywords(bound: &mut Vec<(Value, Value)>, keywords: impl Iterator name - .to_str_heap(vm.heap, vm.interns) + .try_to_str_heap(vm.heap, vm.interns) .ok() .and_then(|name| index.get(name).copied()), None => keyword_index(bound, &name, vm), @@ -241,7 +241,7 @@ fn merge_keywords(bound: &mut Vec<(Value, Value)>, keywords: impl Iterator, keywords: impl Iterator) -> Option { - let name = name.to_str_heap(vm.heap, vm.interns).ok()?; - bound - .iter() - .position(|(bound, _)| bound.to_str_heap(vm.heap, vm.interns).is_ok_and(|bound| bound == name)) + let name = name.as_str_heap(vm.heap, vm.interns)?; + bound.iter().position(|(bound, _)| { + bound + .as_str_heap(vm.heap, vm.interns) + .is_some_and(|bound| bound == name) + }) } /// Maps each bound keyword name to its position, for [`merge_keywords`]. @@ -270,7 +272,7 @@ fn keyword_index_map(bound: &[(Value, Value)], vm: &VM<'_>) -> AHashMap PyTrait<'h> for HeapObjectRead<'h, Partial> { let mut item = 0; 'items: { for index in 0..self.get(vm.heap).args.len() { - // bashkit fork: `?` so a time hit errors instead of truncating (see `repr_check_time`). - if repr_check_time(item, vm)? { + if repr_should_truncate(item, vm)? { f.write_str(", ...[timeout]")?; break 'items; } @@ -384,8 +385,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Partial> { } for index in 0..self.get(vm.heap).keywords.len() { - // bashkit fork: `?` so a time hit errors instead of truncating (see `repr_check_time`). - if repr_check_time(item, vm)? { + if repr_should_truncate(item, vm)? { f.write_str(", ...[timeout]")?; break 'items; } @@ -397,7 +397,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Partial> { // CPython writes the name unquoted, as keyword syntax rather than // as a dict key. The `repr` fallback is for a non-`str` name, which // Monty rejects at the `**` unpack before it can reach a partial. - if let Ok(name) = name.to_str_heap(vm.heap, vm.interns) { + if let Ok(name) = name.try_to_str_heap(vm.heap, vm.interns) { write!(f, ", {name}=")?; } else { f.write_str(", ")?; @@ -565,3 +565,39 @@ fn deep_copy_keywords<'h>( } Ok(()) } + +#[cfg(test)] +mod tests { + use monty_types::{PrintWriter, ResourceTracker}; + + use super::*; + use crate::{ + heap::{Heap, HeapReader}, + run::{Program, SessionTables}, + types::str::allocate_string, + }; + + #[test] + fn keyword_indexes_ignore_non_string_names_until_binding() { + let mut heap = Heap::new(16, ResourceTracker::default()); + let mut tables = SessionTables::default(); + let program = Program::for_tests(); + + HeapReader::with(&mut heap, &mut (&program, &mut tables), |reader, (program, tables)| { + let vm = &mut VM::new(Vec::new(), tables, program, reader, PrintWriter::Disabled); + let bound = vec![ + (Value::Int(1), Value::Int(10)), + (allocate_string("key", vm.heap), Value::Int(20)), + ]; + defer_drop!(bound, vm); + let key = allocate_string("key", vm.heap); + defer_drop!(key, vm); + + assert_eq!(keyword_index(bound, key, vm), Some(1)); + assert_eq!(keyword_index(bound, &Value::Int(1), vm), None); + let index = keyword_index_map(bound, vm); + assert_eq!(index.len(), 1); + assert_eq!(index.get("key"), Some(&1)); + }); + } +} diff --git a/crates/bashkit-monty/src/types/path.rs b/crates/bashkit-monty/src/types/path.rs index 00bf7e059..ef648d48f 100644 --- a/crates/bashkit-monty/src/types/path.rs +++ b/crates/bashkit-monty/src/types/path.rs @@ -79,10 +79,14 @@ impl Path { /// Returns the final component of the path. /// - /// Returns an empty string if the path ends with a separator or is empty. + /// Returns an empty string for `.`, the root, or an empty path. #[must_use] pub fn name(&self) -> &str { - self.path.rsplit_once('/').map_or(self.path.as_str(), |(_, name)| name) + if self.path == "." { + "" + } else { + self.path.rsplit_once('/').map_or(self.path.as_str(), |(_, name)| name) + } } /// Returns the path without its final component (parent directory). @@ -156,10 +160,10 @@ impl Path { /// Returns the path components as a list of strings. /// - /// Absolute paths start with "/" as the first component. + /// Absolute paths start with "/" as the first component; `.` has no parts. #[must_use] pub fn parts(&self) -> Vec<&str> { - if self.path.is_empty() { + if self.path.is_empty() || self.path == "." { return Vec::new(); } @@ -408,7 +412,7 @@ fn path_glob( } /// Extracts a string from a Value for use as a path. -fn extract_path_string<'a>(val: &Value, vm: &'a VM<'_>) -> RunResult<&'a str> { +fn extract_path_string<'a>(val: &'a Value, vm: &'a VM<'_>) -> RunResult<&'a str> { value_as_path_str(val, vm.heap, vm.interns) .ok_or_else(|| ExcType::type_error(format!("expected str or Path, got {}", val.py_type_name(vm)))) } @@ -440,6 +444,7 @@ fn path_rdiv(path: &Path, other: &Value, heap: &Heap, interns: &Interns) -> Opti /// - Removes `.` components (e.g. `/a/./b` → `/a/b`) /// - Collapses consecutive slashes (e.g. `//a///b` → `/a/b`) /// - Removes trailing slashes (except for root "/") +/// - Turns a path with no components (`''`, `'.'`, `'./'`) into `.` /// - Does NOT resolve `..` components (that requires I/O for symlinks) fn normalize_path(mut path: String) -> String { // Convert backslashes to forward slashes @@ -447,8 +452,8 @@ fn normalize_path(mut path: String) -> String { path = path.replace('\\', "/"); } - // Fast path: no `.` component and no consecutive or trailing slashes - if !path.contains("/.") && !path.contains("//") && !path.starts_with("./") { + // Fast path: non-empty, no `.` component and no consecutive or trailing slashes + if !path.is_empty() && !path.contains("/.") && !path.contains("//") && !path.starts_with("./") { // Still strip trailing slashes while path.len() > 1 && path.ends_with('/') { path.pop(); diff --git a/crates/bashkit-monty/src/types/py_trait.rs b/crates/bashkit-monty/src/types/py_trait.rs index c66bedeaf..5d11d2811 100644 --- a/crates/bashkit-monty/src/types/py_trait.rs +++ b/crates/bashkit-monty/src/types/py_trait.rs @@ -1,4 +1,4 @@ -use std::{borrow::Cow, cmp::Ordering, fmt::Write}; +use std::{borrow::Cow, cmp::Ordering, fmt::Write, str}; use ahash::AHashSet; @@ -481,7 +481,7 @@ pub(crate) trait PyTrait<'h>: PyObjectIdentity { /// /// # Returns /// - /// Returns `Ok(true)` if the operation was successful, `Ok(false)` if not supported + /// Returns `Ok(true)` if the operation was handled, `Ok(false)` if not supported /// (the VM then falls back to `py_add`), or `Err` if the operation raised — including /// types whose `+=` is `extend` (e.g. `deque`), which raise `TypeError` from the /// iterator protocol rather than a `ResourceError`. @@ -489,6 +489,11 @@ pub(crate) trait PyTrait<'h>: PyObjectIdentity { Ok(false) } + /// Mutates in place for `*=`, or returns false to use ordinary multiplication. + fn py_imul_impl(&mut self, _other: &Value, _vm: &mut VM<'h>) -> RunResult { + Ok(false) + } + /// Python in-place subtraction (`__isub__`), with [`py_iadd_impl`](Self::py_iadd_impl)'s /// contract: `Ok(true)` mutated `self` in place, `Ok(false)` falls back to binary `-`. fn py_isub_impl(&mut self, _other: &Value, _vm: &mut VM<'h>) -> RunResult { @@ -505,6 +510,11 @@ pub(crate) trait PyTrait<'h>: PyObjectIdentity { Ok(false) } + /// Mutates in place for `^=`, or returns false to use binary XOR. + fn py_ixor_impl(&mut self, _other: &Value, _vm: &mut VM<'h>) -> RunResult { + Ok(false) + } + /// Calls this value itself (`obj(...)`), the counterpart of /// [`py_call_attr`](Self::py_call_attr) for the callable rather than one of /// its methods. @@ -726,14 +736,6 @@ pub(crate) trait PyTrait<'h>: PyObjectIdentity { } } -/// Converts an attribute name into an owned dict key, preserving interned names. -pub(crate) fn attribute_name_value(name: &EitherStr, vm: &VM<'_>) -> Value { - match name { - EitherStr::Interned(string_id) => Value::InternString(*string_id), - EitherStr::Heap(s) => allocate_string(s.as_str(), vm.heap), - } -} - /// Lazy wrapper around [`AHashSet`] that only allocates the set when needed. #[derive(Default, Debug, Clone)] pub(crate) struct LazyHeapSet(Option>); diff --git a/crates/bashkit-monty/src/types/re_match.rs b/crates/bashkit-monty/src/types/re_match.rs index 4818e7689..ed0a4f14b 100644 --- a/crates/bashkit-monty/src/types/re_match.rs +++ b/crates/bashkit-monty/src/types/re_match.rs @@ -77,48 +77,39 @@ pub(crate) struct ReMatch { } impl ReMatch { - /// Creates a `ReMatch` from a `fancy_regex::Captures` result. + /// Creates a `ReMatch` from the byte spans of one match: `spans[0]` is the full + /// match, then one entry per capture group (`None` if it took no part). /// - /// Stores byte offsets (converted to char offsets lazily — see the type docs). - /// `subject` is the already-refcounted subject `Value` this match keeps alive - /// (the caller clones it per match); `regex` supplies named-group mappings. - pub fn from_captures( - // bashkit fork: fancy-regex 0.20 made `Captures` generic over the - // haystack type; the fork is ahead of upstream's 0.17 (see Cargo.toml). - caps: &fancy_regex::Captures<'_, str>, + /// Taking spans rather than `fancy_regex::Captures` lets `finditer` hold a flat, + /// fixed-size span buffer while it scans. `text` is the searched string; `subject` + /// is its already-refcounted `Value` (the caller clones it per match); `regex` + /// supplies named-group mappings. + pub fn from_spans( + text: &str, + spans: &[Option<(usize, usize)>], subject: Value, all_ascii: bool, regex: &fancy_regex::Regex, ) -> Self { - let full = caps.get(0).expect("group 0 always exists on a successful match"); - let full_match = full.as_str().to_owned(); - let start = full.start(); - let end = full.end(); - - let group_count = caps.len().saturating_sub(1); - let mut groups = Vec::with_capacity(group_count); - let mut group_spans = Vec::with_capacity(group_count); - - for cap in caps.iter().skip(1) { - if let Some(m) = cap { - groups.push(Some(m.as_str().to_owned())); - group_spans.push(Some((m.start(), m.end()))); - } else { - groups.push(None); - group_spans.push(None); - } - } - - // Extract named group name→index mappings from the regex - let mut named_groups = Vec::new(); - for (idx, name) in regex.capture_names().enumerate() { - if let Some(name) = name { - named_groups.push((name.to_owned(), idx)); - } - } + let (start, end) = spans[0].expect("group 0 always exists on a successful match"); + let group_spans = spans[1..].to_vec(); + let groups = group_spans + .iter() + .map(|span| span.map(|(s, e)| text[s..e].to_owned())) + .collect(); + + // Extract named group name→index mappings from the regex, sized exactly as + // `estimated_size` charges: `filter_map` would `collect` into at least 4 slots. + let mut named_groups = Vec::with_capacity(regex.capture_names().flatten().count()); + named_groups.extend( + regex + .capture_names() + .enumerate() + .filter_map(|(idx, name)| name.map(|name| (name.to_owned(), idx))), + ); Self { - full_match, + full_match: text[start..end].to_owned(), start, end, groups, @@ -130,6 +121,18 @@ impl ReMatch { } } + /// Estimates the bytes [`from_spans`](Self::from_spans) allocates for one match + /// with `group_count` groups and `names_len` bytes of group names over `name_count` + /// names, excluding its heap slot and the matched text it copies. + /// + /// `finditer` sums this over every match to preflight the pass that builds them. + pub fn estimated_size(group_count: usize, name_count: usize, names_len: usize) -> usize { + size_of::() + + group_count * (size_of::>() + size_of::>()) + + name_count * size_of::<(String, usize)>() + + names_len + } + /// The subject `Value` this match keeps alive (its `.string`). Lets the heap /// walkers in `heap.rs` follow and release the shared subject reference. pub(crate) fn subject_ref(&self) -> &Value { @@ -144,7 +147,7 @@ impl ReMatch { let (start, end) = if self.all_ascii { (self.start, self.end) } else { - let text = self.subject.to_str(vm).expect("subject is always a str"); + let text = self.subject.try_to_str(vm).expect("subject is always a str"); let start = byte_to_char_offset(text, self.start); // Count only the matched slice for `end` instead of rescanning from zero. (start, start + text[self.start..self.end].chars().count()) @@ -162,7 +165,7 @@ impl ReMatch { let char_offset = if self.all_ascii { byte_offset } else { - let text = self.subject.to_str(vm).expect("subject is always a str"); + let text = self.subject.try_to_str(vm).expect("subject is always a str"); byte_to_char_offset(text, byte_offset) }; position_i64(char_offset) @@ -385,18 +388,10 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, ReMatch> { match key { Value::Int(n) => self.get(vm.heap).get_group(*n, vm.heap), Value::Bool(b) => self.get(vm.heap).get_group(i64::from(*b), vm.heap), - Value::InternString(id) => { - let name = vm.interns.get_str(*id); - self.get(vm.heap).get_group_by_name(name, vm.heap) - } - Value::Ref(heap_id) => match vm.heap.get(*heap_id) { - HeapData::Str(s) => { - let name = s.as_str().to_owned(); - self.get(vm.heap).get_group_by_name(&name, vm.heap) - } - _ => Err(ExcType::re_match_group_index_error()), + _ => match key.as_str(vm) { + Some(name) => self.get(vm.heap).get_group_by_name(name, vm.heap), + None => Err(ExcType::re_match_group_index_error()), }, - _ => Err(ExcType::re_match_group_index_error()), } } } @@ -446,18 +441,10 @@ fn resolve_group_arg(m: &ReMatch, val: &Value, vm: &VM<'_>) -> RunResult match val { Value::Int(n) => m.get_group(*n, vm.heap), Value::Bool(b) => m.get_group(i64::from(*b), vm.heap), - Value::InternString(id) => { - let name = vm.interns.get_str(*id); - m.get_group_by_name(name, vm.heap) - } - Value::Ref(heap_id) => match vm.heap.get(*heap_id) { - HeapData::Str(s) => { - let name = s.as_str().to_owned(); - m.get_group_by_name(&name, vm.heap) - } - _ => Err(ExcType::re_match_group_index_error()), + _ => match val.as_str(vm) { + Some(name) => m.get_group_by_name(name, vm.heap), + None => Err(ExcType::re_match_group_index_error()), }, - _ => Err(ExcType::re_match_group_index_error()), } } diff --git a/crates/bashkit-monty/src/types/re_pattern.rs b/crates/bashkit-monty/src/types/re_pattern.rs index f7821a582..f110def7e 100644 --- a/crates/bashkit-monty/src/types/re_pattern.rs +++ b/crates/bashkit-monty/src/types/re_pattern.rs @@ -6,6 +6,9 @@ //! to ReDoS. Monty's resource limits (time and allocation budgets) are the primary defense //! against catastrophic backtracking in untrusted patterns. //! +//! Patterns are translated from CPython's syntax by [`re_syntax::translate`] before `fancy_regex` +//! sees them, so CPython's errors are raised and `fancy_regex`'s own extensions are unreachable. +//! //! Custom serde serializes only the pattern string and flags, recompiling the regex //! on deserialization. This supports Monty's snapshot/restore feature. @@ -13,18 +16,19 @@ use std::{borrow::Cow, cell::OnceCell, cmp::Ordering, fmt::Write, iter, mem, str use fancy_regex::{CompileError, Error as RegexError, Regex, RegexBuilder}; use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; +use smallvec::SmallVec; use crate::{ args::{ArgValues, FromArgs}, bytecode::{CallResult, VM}, defer_drop, exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, - heap::{Heap, HeapData, HeapId, HeapItem, HeapObjectRead, HeapRead, HeapReadOutput}, + heap::{HEAP_ENTRY_SIZE, Heap, HeapData, HeapId, HeapItem, HeapObjectRead, HeapRead, HeapReadOutput}, intern::StaticStrings, modules::re::{ASCII, DOTALL, IGNORECASE, MULTILINE}, resource_checks::check_estimated_size, types::{ - LazyHeapSet, List, PyTrait, ReMatch, Type, allocate_tuple, + LazyHeapSet, List, PyTrait, ReMatch, Type, allocate_tuple, re_syntax, str::{allocate_string, string_repr_fmt}, tuple::TupleVec, }, @@ -99,7 +103,8 @@ impl RePattern { /// /// Returns `re.PatternError` if the pattern is invalid. pub fn compile(pattern: String, flags: u16) -> RunResult { - Self::compile_inner(pattern, flags, None).map_err(ExcType::re_pattern_error) + let source = re_syntax::translate(&pattern, flags)?; + Self::compile_inner(pattern, &source, flags, None).map_err(ExcType::re_pattern_error) } /// As [`RePattern::compile`], but caps the compiled size of the delegated regex @@ -112,7 +117,8 @@ impl RePattern { flags: u16, delegate_size_limit: usize, ) -> Result { - Self::compile_inner(pattern, flags, Some(delegate_size_limit)).map_err(|err| { + let source = re_syntax::translate(&pattern, flags).map_err(BoundedCompileError::Invalid)?; + Self::compile_inner(pattern, &source, flags, Some(delegate_size_limit)).map_err(|err| { if is_size_limit_error(&err) { BoundedCompileError::TooBig } else { @@ -131,8 +137,15 @@ impl RePattern { } /// Shared constructor for [`RePattern::compile`] / [`RePattern::compile_bounded`]. - fn compile_inner(pattern: String, flags: u16, delegate_size_limit: Option) -> Result { - let compiled = compile_regex_limited(&pattern, flags, delegate_size_limit)?; + /// + /// `source` is `pattern` translated by [`re_syntax::translate`]. + fn compile_inner( + pattern: String, + source: &str, + flags: u16, + delegate_size_limit: Option, + ) -> Result { + let compiled = compile_regex_limited(source, flags, delegate_size_limit)?; Ok(Self { pattern, flags, @@ -145,18 +158,16 @@ impl RePattern { /// Returns the `\A(?:pattern)` regex for `match()`, compiling it on first use. /// + /// The pattern is translated again rather than kept, since cached patterns should stay small. /// Wrapping a pattern that already compiled essentially never fails, so any /// error surfaces (as `re.PatternError`) at `match()` rather than `re.compile()`. fn match_regex(&self) -> RunResult<&Regex> { if let Some(regex) = self.compiled_match.get() { return Ok(regex); } - let compiled = compile_regex_limited( - &anchored_source(&self.pattern, ""), - self.flags, - self.delegate_size_limit, - ) - .map_err(ExcType::re_pattern_error)?; + let source = re_syntax::translate(&self.pattern, self.flags)?; + let compiled = compile_regex_limited(&anchored_source(&source, ""), self.flags, self.delegate_size_limit) + .map_err(ExcType::re_pattern_error)?; // `set` only fails on a concurrent init, impossible on the single-threaded VM. let _ = self.compiled_match.set(compiled); Ok(self.compiled_match.get().expect("cell was just initialised")) @@ -167,33 +178,52 @@ impl RePattern { if let Some(regex) = self.compiled_fullmatch.get() { return Ok(regex); } - let compiled = compile_regex_limited( - &anchored_source(&self.pattern, "\\z"), - self.flags, - self.delegate_size_limit, - ) - .map_err(ExcType::re_pattern_error)?; + let source = re_syntax::translate(&self.pattern, self.flags)?; + let compiled = compile_regex_limited(&anchored_source(&source, "\\z"), self.flags, self.delegate_size_limit) + .map_err(ExcType::re_pattern_error)?; let _ = self.compiled_fullmatch.set(compiled); Ok(self.compiled_fullmatch.get().expect("cell was just initialised")) } - /// Builds a single `ReMatch` heap value from a capture result, keeping the - /// subject alive by refcount (`subject.clone_with_heap`) rather than copying - /// its text. `all_ascii` is precomputed by the caller (once per `finditer`). - // bashkit fork: fancy-regex 0.20 made `Captures` generic over the haystack - // type; the fork is ahead of upstream's 0.17 (see Cargo.toml). - fn build_match(&self, caps: &fancy_regex::Captures<'_, str>, subject: &Value, all_ascii: bool, heap: &Heap) -> Value { - let m = ReMatch::from_captures(caps, subject.clone_with_heap(heap), all_ascii, &self.compiled); + /// Builds a single `ReMatch` heap value from one match's spans (see + /// [`ReMatch::from_spans`]), keeping the subject alive by refcount + /// (`subject.clone_with_heap`) rather than copying its text. `all_ascii` is + /// precomputed by the caller (once per `finditer`). + fn build_match( + &self, + text: &str, + spans: &[Option<(usize, usize)>], + subject: &Value, + all_ascii: bool, + heap: &Heap, + ) -> Value { + let m = ReMatch::from_spans(text, spans, subject.clone_with_heap(heap), all_ascii, &self.compiled); Value::Ref(heap.allocate(HeapData::ReMatch(Box::new(m)))) } + /// Builds the `ReMatch` for a single-match search (`search`, `match`, `fullmatch`). + /// + /// The spans sit on the stack for patterns with up to seven groups, so a search + /// allocates nothing beyond the match itself. + fn build_single_match( + &self, + text: &str, + caps: &fancy_regex::Captures<'_, str>, + subject: &Value, + heap: &Heap, + ) -> Value { + let spans: SmallVec<[Option<(usize, usize)>; 8]> = + caps.iter().map(|m| m.map(|m| (m.start(), m.end()))).collect(); + self.build_match(text, &spans, subject, text.is_ascii(), heap) + } + /// `pattern.search(string)` — find first match anywhere in the string. /// /// `subject` is the subject `Value` (stored by the match); `text` is its /// borrowed contents. Returns a `ReMatch` heap object, or `Value::None`. pub fn search(&self, subject: &Value, text: &str, heap: &Heap) -> RunResult { match self.compiled.captures(text) { - Ok(Some(caps)) => Ok(self.build_match(&caps, subject, text.is_ascii(), heap)), + Ok(Some(caps)) => Ok(self.build_single_match(text, &caps, subject, heap)), Ok(None) => Ok(Value::None), Err(err) => Err(ExcType::re_pattern_error(err)), } @@ -208,7 +238,7 @@ impl RePattern { /// Returns a `ReMatch` heap object on success, or `Value::None` if no match. pub fn match_start(&self, subject: &Value, text: &str, heap: &Heap) -> RunResult { match self.match_regex()?.captures(text) { - Ok(Some(caps)) => Ok(self.build_match(&caps, subject, text.is_ascii(), heap)), + Ok(Some(caps)) => Ok(self.build_single_match(text, &caps, subject, heap)), Ok(None) => Ok(Value::None), Err(err) => Err(ExcType::re_pattern_error(err)), } @@ -223,7 +253,7 @@ impl RePattern { /// Returns a `ReMatch` heap object on success, or `Value::None` if no match. pub fn fullmatch(&self, subject: &Value, text: &str, heap: &Heap) -> RunResult { match self.fullmatch_regex()?.captures(text) { - Ok(Some(caps)) => Ok(self.build_match(&caps, subject, text.is_ascii(), heap)), + Ok(Some(caps)) => Ok(self.build_single_match(text, &caps, subject, heap)), Ok(None) => Ok(Value::None), Err(err) => Err(ExcType::re_pattern_error(err)), } @@ -366,41 +396,66 @@ impl RePattern { /// `pattern.finditer(string)` — return all matches as a list. /// - /// Eagerly collects all match objects into a list. This differs from CPython's - /// lazy iterator but produces the same results when iterated. The VM's `GetIter` - /// opcode handles iteration over the returned list. + /// Unlike CPython's lazy `callable_iterator`, every match is found and built when + /// `finditer` is called, so errors are raised by the call itself, `next()` on the + /// result raises `TypeError`, and the list can be iterated again. + /// + /// The scan records each match's spans in one flat buffer, so its growth checks + /// see the whole cost, and a scan error leaves no half-built match objects behind. + /// The build pass that follows is preflighted as a whole, since it cannot stop + /// part way without leaking the matches it has built. pub fn finditer(&self, subject: &Value, text: &str, heap: &Heap) -> RunResult { - // Every match shares one refcounted subject reference, not a copy each. - let all_ascii = text.is_ascii(); - - let mut results = Vec::new(); - for caps in self.compiled.captures_iter(text) { - check_results_growth(&results, heap)?; + let stride = self.compiled.captures_len(); + let mut spans: Vec> = Vec::new(); + let mut text_len = 0usize; + for (count, caps) in self.compiled.captures_iter(text).enumerate() { let caps = caps.map_err(ExcType::re_pattern_error)?; - results.push(self.build_match(&caps, subject, all_ascii, heap)); + // `check_slice_growth` for a push of `stride` spans at once. + heap.tracker.check_time_every(count)?; + heap.tracker.check_growth( + spans.len() + stride - 1, + spans.capacity(), + mem::size_of::>(), + )?; + spans.reserve(stride); + push_spans(&caps, &mut spans); + // Saturating: on 32-bit targets overlapping captures can sum past `usize::MAX`. + text_len = caps + .iter() + .flatten() + .fold(text_len, |total, m| total.saturating_add(m.end() - m.start())); } - let list = List::new(results); - Ok(Value::Ref(heap.allocate(HeapData::List(list)))) + let count = spans.len() / stride; + let (name_count, names_len) = self + .compiled + .capture_names() + .flatten() + .fold((0, 0), |(count, len), name| (count + 1, len + name.len())); + let per_match = VALUE_SIZE + HEAP_ENTRY_SIZE + ReMatch::estimated_size(stride - 1, name_count, names_len); + heap.tracker + .check_allocation(count.saturating_mul(per_match).saturating_add(text_len))?; + // Every match shares one refcounted subject reference, not a copy each. + let all_ascii = text.is_ascii(); + let results = spans + .chunks_exact(stride) + .map(|spans| self.build_match(text, spans, subject, all_ascii, heap)) + .collect(); + Ok(Value::Ref(heap.allocate(HeapData::List(List::new(results))))) } } -/// Preflights the growth one more match result would cause. -/// -/// A match list grows as long as the subject allows with no instruction -/// checkpoint in between, so without this the buffer's doubling can clear the -/// allocator's hard-limit headroom and kill the worker. -fn check_results_growth(results: &Vec, heap: &Heap) -> RunResult<()> { - Ok(heap - .tracker - .check_growth(results.len(), results.capacity(), VALUE_SIZE)?) +/// Appends one match's byte spans to `spans`: the full match, then each group. +fn push_spans(caps: &fancy_regex::Captures<'_, str>, spans: &mut Vec>) { + spans.extend(caps.iter().map(|m| m.map(|m| (m.start(), m.end())))); } -/// [`check_results_growth`] for a buffer of borrowed match slices (`&str`, or -/// `Option<&str>` where a split's group may be missing). +/// Preflights the growth one more scan result would cause, for a buffer of borrowed +/// match slices (`&str`, or `Option<&str>` where a split's group may be missing). /// -/// Also polls the time limit, amortized with `check_time_every`: no instruction -/// checkpoint can stop the scan that fills the buffer either. +/// A scan buffer grows as long as the subject allows with no instruction checkpoint +/// in between, so without this its doubling can clear the allocator's hard-limit +/// headroom and kill the worker. Also polls the time limit, amortized with `check_time_every`. fn check_slice_growth(slices: &Vec, heap: &Heap) -> RunResult<()> { heap.tracker.check_time_every(slices.len())?; Ok(heap @@ -484,7 +539,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, RePattern> { write!(f, "re.compile(")?; string_repr_fmt(&this.pattern, f)?; if this.flags != 0 { - let mut flag_parts = smallvec::SmallVec::<[&'static str; 4]>::new(); + let mut flag_parts = SmallVec::<[&'static str; 4]>::new(); if this.flags & IGNORECASE != 0 { flag_parts.push("re.IGNORECASE"); } @@ -518,25 +573,25 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, RePattern> { Some(StaticStrings::Search) => { let arg = args.get_one_arg("Pattern.search", vm.heap)?; defer_drop!(arg, vm); - let text = arg.to_str(vm)?; + let text = arg.try_to_str(vm)?; self.get(vm.heap).search(arg, text, vm.heap) } Some(StaticStrings::Match) => { let arg = args.get_one_arg("Pattern.match", vm.heap)?; defer_drop!(arg, vm); - let text = arg.to_str(vm)?; + let text = arg.try_to_str(vm)?; self.get(vm.heap).match_start(arg, text, vm.heap) } Some(StaticStrings::Fullmatch) => { let arg = args.get_one_arg("Pattern.fullmatch", vm.heap)?; defer_drop!(arg, vm); - let text = arg.to_str(vm)?; + let text = arg.try_to_str(vm)?; self.get(vm.heap).fullmatch(arg, text, vm.heap) } Some(StaticStrings::Findall) => { let arg = args.get_one_arg("Pattern.findall", vm.heap)?; defer_drop!(arg, vm); - let text = arg.to_str(vm)?; + let text = arg.try_to_str(vm)?; self.get(vm.heap).findall(text, vm.heap) } Some(StaticStrings::Sub) => call_pattern_sub(self, args, vm), @@ -544,7 +599,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, RePattern> { Some(StaticStrings::Finditer) => { let arg = args.get_one_arg("Pattern.finditer", vm.heap)?; defer_drop!(arg, vm); - let text = arg.to_str(vm)?; + let text = arg.try_to_str(vm)?; self.get(vm.heap).finditer(arg, text, vm.heap) } _ => return Err(ExcType::attribute_error_method(Type::RePattern, attr, args, vm)), @@ -579,7 +634,7 @@ fn call_pattern_sub<'h>(pattern: &HeapRead<'h, RePattern>, args: ArgValues, vm: // CPython processes the replacement template *before* its match loop, so // this check must precede the negative-count early return below: a bad // repl raises even when zero substitutions will run. - let Ok(repl) = repl_val.to_str(vm) else { + let Ok(repl) = repl_val.try_to_str(vm) else { return Err(ExcType::type_error( "callable replacement is not yet supported in re.sub()", )); @@ -588,14 +643,14 @@ fn call_pattern_sub<'h>(pattern: &HeapRead<'h, RePattern>, args: ArgValues, vm: // Validate octal escapes even when the negative count skips matching. translate_replacement(repl)?; // Negative count — Pattern.sub returns the input string unchanged. - // The subject is still type-checked (`to_str` raises this method's + // The subject is still type-checked (`try_to_str` raises this method's // `expected string, not {t}` wording) before the refcount bump; no // need to re-allocate. - let _ = string_val.to_str(vm)?; + let _ = string_val.try_to_str(vm)?; return Ok(string_val.clone_with_heap(vm.heap)); }; - let text = string_val.to_str(vm)?; + let text = string_val.try_to_str(vm)?; pattern.get(vm.heap).sub(repl, text, count, vm.heap) } @@ -610,7 +665,7 @@ fn call_pattern_split<'h>(pattern: &HeapRead<'h, RePattern>, args: ArgValues, vm defer_drop!(string_val, vm); let maxsplit = extract_maxsplit(maxsplit_val, vm)?; - let text = string_val.to_str(vm)?.to_owned(); + let text = string_val.try_to_str(vm)?.to_owned(); pattern.get(vm.heap).split(&text, maxsplit, vm.heap) } @@ -700,7 +755,7 @@ fn anchored_source(pattern: &str, suffix: &str) -> String { format!("\\A(?:{pattern}(?x)\n){suffix}") } -/// Compiles a Python regex pattern string with flags into a Rust `Regex`. +/// Compiles a pattern already translated by [`re_syntax::translate`], with flags, into a Rust `Regex`. /// /// Translates Python flag constants into inline regex flag prefixes: /// - `re.IGNORECASE` (2) → `(?i)` prefix @@ -739,12 +794,16 @@ fn compile_regex_limited(pattern: &str, flags: u16, delegate_size_limit: Option< }; let mut builder = RegexBuilder::new(&full_pattern); + builder.max_prog_size(MAX_PROG_SIZE); if let Some(limit) = delegate_size_limit { builder.delegate_size_limit(limit); } builder.build() } +/// Cap on the backtracking VM's instructions; translated patterns grow it only linearly with their length. +const MAX_PROG_SIZE: usize = 1_000_000; + /// True when `err` is the delegated engine's exceeded-size-limit error: the /// pattern is valid, its compiled form just doesn't fit the requested cap. fn is_size_limit_error(err: &RegexError) -> bool { diff --git a/crates/bashkit-monty/src/types/re_syntax.rs b/crates/bashkit-monty/src/types/re_syntax.rs new file mode 100644 index 000000000..179e7f7a0 --- /dev/null +++ b/crates/bashkit-monty/src/types/re_syntax.rs @@ -0,0 +1,1149 @@ +//! Translation of CPython `re` pattern syntax into `fancy-regex` syntax. +//! +//! `fancy-regex` accepts Oniguruma and PCRE extensions that CPython rejects, among them subroutine calls, +//! whose compile-time expansion is unbounded. It also reads some shared syntax differently: `\<` and `\Z`, +//! octal escapes, and set operators inside classes. +//! [`translate`] parses a pattern the way CPython's `re._parser` does, raising its errors with the same +//! messages and positions, and emits an equivalent pattern built only from syntax both engines agree on. +//! Literal punctuation is emitted as `\x{..}`, so nothing in the output can be read as an extension. + +use std::{ + collections::HashMap, + fmt::{self, Write}, +}; + +use crate::{ + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + modules::re::{ASCII, DOTALL, IGNORECASE, MULTILINE}, + types::str::{StringRepr, str_isidentifier}, +}; + +/// `re.LOCALE`, which CPython rejects for str patterns. +const LOCALE: u16 = 4; +/// `re.UNICODE`, incompatible with `re.ASCII`. +const UNICODE: u16 = 32; +/// `re.VERBOSE`: whitespace and `#` comments outside classes are ignored. +const VERBOSE: u16 = 64; +/// The flags that pick how character classes behave; at most one may be set. +const TYPE_FLAGS: u16 = ASCII | LOCALE | UNICODE; + +/// CPython's `MAXREPEAT`: repeat counts must be below it, and it stands for "unbounded". +const MAXREPEAT: u64 = 4_294_967_295; +/// CPython's `MAXGROUPS`; a conditional naming a group at or above it is invalid. +const MAXGROUPS: u64 = 1_073_741_823; +/// CPython's `MAXCODE`: the furthest a lookbehind may look. +const MAXCODE: u128 = 4_294_967_295; +/// CPython's `MAXWIDTH`, the saturation point of subpattern widths. +const MAXWIDTH: u128 = 1 << 64; +/// Group nesting at which `fancy-regex` gives up; checked here first so the recursion stays bounded. +const MAX_NESTING: usize = 64; + +/// Translates a CPython regex `pattern` into `fancy-regex` syntax, validating it as CPython does. +/// +/// `flags` are the `flags=` argument; they are not applied to the output, only checked for consistency +/// with inline flags (the caller prefixes the flag groups itself). +/// +/// # Errors +/// +/// `re.PatternError` with CPython's message for an invalid pattern, `OverflowError` for a repeat count +/// that is too large and `ValueError` for incompatible flags. +pub(crate) fn translate(pattern: &str, flags: u16) -> RunResult { + let mut translator = Translator::new(pattern, flags)?; + translator.parse_sub(flags & VERBOSE != 0, 0)?; + translator.finish() +} + +/// One token of the pattern: a character, or a backslash and the character after it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Token { + Char(char), + Escape(char), +} + +impl Token { + /// Length of the token in pattern characters, which is what CPython's error positions count. + fn len(self) -> usize { + match self { + Self::Char(_) => 1, + Self::Escape(_) => 2, + } + } + + /// The character after the backslash, or the character itself. + fn char(self) -> char { + match self { + Self::Char(c) | Self::Escape(c) => c, + } + } +} + +impl fmt::Display for Token { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Char(c) => write!(f, "{c}"), + Self::Escape(c) => write!(f, "\\{c}"), + } + } +} + +/// A port of CPython's `re._parser.Tokenizer`: one token of lookahead over the pattern's characters. +struct Tokenizer { + chars: Vec, + /// Index just past `next`. + index: usize, + next: Option, +} + +impl Tokenizer { + fn new(pattern: &str) -> RunResult { + let mut tokenizer = Self { + chars: pattern.chars().collect(), + index: 0, + next: None, + }; + tokenizer.advance()?; + Ok(tokenizer) + } + + /// Reads the token at `index` into `next`. + fn advance(&mut self) -> RunResult<()> { + self.next = match self.chars.get(self.index) { + None => None, + Some('\\') => match self.chars.get(self.index + 1) { + Some(&c) => Some(Token::Escape(c)), + None => { + return Err(self.error_at("bad escape (end of pattern)", self.chars.len() - 1)); + } + }, + Some(&c) => Some(Token::Char(c)), + }; + self.index += self.next.map_or(0, Token::len); + Ok(()) + } + + /// Consumes and returns the next token. + fn get(&mut self) -> RunResult> { + let this = self.next; + self.advance()?; + Ok(this) + } + + /// Consumes the next token if it is the plain character `c`. + fn matches(&mut self, c: char) -> RunResult { + if self.next == Some(Token::Char(c)) { + self.advance()?; + Ok(true) + } else { + Ok(false) + } + } + + /// The next token if it is a plain character. + fn next_char(&self) -> Option { + match self.next { + Some(Token::Char(c)) => Some(c), + _ => None, + } + } + + /// Position of the next token. + fn tell(&self) -> usize { + self.index - self.next.map_or(0, Token::len) + } + + fn seek(&mut self, index: usize) -> RunResult<()> { + self.index = index; + self.advance() + } + + /// Consumes up to `n` plain characters matching `accept`. + fn get_while(&mut self, n: usize, accept: impl Fn(char) -> bool) -> RunResult { + let mut result = String::new(); + for _ in 0..n { + match self.next_char() { + Some(c) if accept(c) => { + result.push(c); + self.advance()?; + } + _ => break, + } + } + Ok(result) + } + + /// Consumes tokens up to and including `terminator`, returning the text before it. + /// + /// `name` describes the text for the "missing ..." errors. + fn get_until(&mut self, terminator: char, name: &str) -> RunResult { + let mut result = String::new(); + let mut len = 0; + loop { + match self.get()? { + None if result.is_empty() => return Err(self.error(format!("missing {name}"), 0)), + None => return Err(self.error(format!("missing {terminator}, unterminated name"), len)), + Some(Token::Char(c)) if c == terminator => { + return if result.is_empty() { + Err(self.error(format!("missing {name}"), 1)) + } else { + Ok(result) + }; + } + Some(token) => { + result.push_str(&token.to_string()); + len += token.len(); + } + } + } + } + + /// Rejects a group name that is not an identifier. + fn check_group_name(&self, name: &str, offset: usize) -> RunResult<()> { + if str_isidentifier(name) { + Ok(()) + } else { + let msg = format!("bad character in group name {}", StringRepr(name)); + Err(self.error(msg, name.chars().count() + offset)) + } + } + + /// A `re.PatternError` at `offset` characters before the next token. + fn error(&self, msg: impl fmt::Display, offset: usize) -> RunError { + self.error_at(msg, self.tell().saturating_sub(offset)) + } + + /// A `re.PatternError` at `pos`, formatted as CPython's `PatternError.__init__` does. + fn error_at(&self, msg: impl fmt::Display, pos: usize) -> RunError { + let before = &self.chars[..pos.min(self.chars.len())]; + let msg = if self.chars.contains(&'\n') { + let line = before.iter().filter(|&&c| c == '\n').count() + 1; + let column = before.iter().rposition(|&c| c == '\n').map_or(pos + 1, |i| pos - i); + format!("{msg} at position {pos} (line {line}, column {column})") + } else { + format!("{msg} at position {pos}") + }; + ExcType::re_pattern_error(msg) + } +} + +/// Smallest and largest number of characters a subpattern can match, saturating at [`MAXWIDTH`]. +type Width = (u128, u128); + +/// What CPython's repeat operators need to know about the item before them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ItemKind { + /// An anchor (`^`, `$`, `\A`, `\b`, ...): nothing to repeat. + At, + /// Already repeated: another quantifier is a "multiple repeat". + Repeat, + Other, +} + +/// One parsed element of a sequence. +#[derive(Debug, Clone, Copy)] +struct Item { + kind: ItemKind, + width: Width, +} + +impl Item { + /// An item matching exactly one character. + const UNIT: Self = Self { + kind: ItemKind::Other, + width: (1, 1), + }; + /// A zero-width anchor. + const AT: Self = Self { + kind: ItemKind::At, + width: (0, 0), + }; + /// A zero-width item that is not an anchor (a lookaround). + const EMPTY: Self = Self { + kind: ItemKind::Other, + width: (0, 0), + }; +} + +/// What a `(` construct contributed to its sequence. +enum GroupOutcome { + Item(Item), + /// A `(?#...)` comment. + Nothing, + /// Global flags such as `(?x)`, which may change verbosity. + GlobalFlags, +} + +/// A member of a character class. +#[derive(Debug, Clone, Copy)] +enum ClassItem { + /// A code point, which may be a surrogate no Monty string contains. + Literal(u32), + Range(u32, u32), + /// `\d`, `\D`, `\s`, `\S`, `\w` or `\W`. + Category(char), +} + +/// Parser state, a port of CPython's `re._parser.State` plus the output being built. +struct Translator { + source: Tokenizer, + out: String, + /// The `flags=` argument plus any global inline flags. + flags: u16, + /// Widths of closed groups by number; `None` while open. Index 0 stands for the whole pattern. + group_widths: Vec>, + group_names: HashMap, + /// Number of groups when the outermost enclosing lookbehind opened. + lookbehind_groups: Option, + /// Groups named by numbered conditionals and where, in order, repeats included; checked once all groups are known. + groupref_pos: Vec<(u64, usize)>, + /// The first lookbehind CPython's compiler would reject, by start position, and its message. + lookbehind_error: Option<(usize, &'static str)>, + depth: usize, +} + +impl Translator { + fn new(pattern: &str, flags: u16) -> RunResult { + Ok(Self { + source: Tokenizer::new(pattern)?, + out: String::with_capacity(pattern.len()), + flags, + group_widths: vec![None], + group_names: HashMap::new(), + lookbehind_groups: None, + groupref_pos: Vec::new(), + lookbehind_error: None, + depth: 0, + }) + } + + /// The checks CPython makes after parsing, in its order; returns the translated pattern. + fn finish(self) -> RunResult { + if self.flags & LOCALE != 0 { + return Err(ExcType::value_error("cannot use LOCALE flag with a str pattern")); + } + if self.flags & ASCII != 0 && self.flags & UNICODE != 0 { + return Err(ExcType::value_error("ASCII and UNICODE flags are incompatible")); + } + if self.source.next.is_some() { + return Err(self.source.error("unbalanced parenthesis", 0)); + } + let groups = self.group_widths.len() as u64; + if let Some(&(group, pos)) = self.groupref_pos.iter().find(|(group, _)| *group >= groups) { + return Err(self.source.error_at(format!("invalid group reference {group}"), pos)); + } + match self.lookbehind_error { + Some((_, msg)) => Err(ExcType::re_pattern_error(msg)), + None => Ok(self.out), + } + } + + /// Parses an alternation, port of `_parse_sub`. + fn parse_sub(&mut self, mut verbose: bool, nested: usize) -> RunResult { + let mut width = (MAXWIDTH, 0); + let mut first = nested == 0; + loop { + let branch = self.parse(verbose, nested + 1, first)?; + width = (width.0.min(branch.0), width.1.max(branch.1)); + if !self.source.matches('|')? { + return Ok(width); + } + self.out.push('|'); + first = false; + if nested == 0 { + verbose = self.flags & VERBOSE != 0; + } + } + } + + /// Parses a sequence up to `|`, `)` or the end, port of `_parse`. + /// + /// `first` is true only for the first top-level branch, where global flags are allowed. + fn parse(&mut self, mut verbose: bool, nested: usize, first: bool) -> RunResult { + let mut items: Vec = Vec::new(); + while let Some(this) = self.source.next { + if matches!(this, Token::Char('|' | ')')) { + break; + } + self.source.advance()?; + if verbose { + match this { + Token::Char(' ' | '\t' | '\n' | '\r' | '\x0b' | '\x0c') => continue, + Token::Char('#') => { + while !matches!(self.source.get()?, None | Some(Token::Char('\n'))) {} + continue; + } + _ => {} + } + } + match this { + Token::Escape(c) => items.push(self.escape(c)?), + Token::Char('[') => { + self.class()?; + items.push(Item::UNIT); + } + Token::Char(c @ ('*' | '+' | '?' | '{')) => self.repeat(c, &mut items)?, + Token::Char('.') => { + self.out.push('.'); + items.push(Item::UNIT); + } + Token::Char('(') => match self.group(verbose, nested, first && items.is_empty())? { + GroupOutcome::Item(item) => items.push(item), + GroupOutcome::Nothing => {} + GroupOutcome::GlobalFlags => verbose = self.flags & VERBOSE != 0, + }, + Token::Char(c @ ('^' | '$')) => { + self.out.push(c); + items.push(Item::AT); + } + Token::Char(c) => { + push_literal(&mut self.out, u32::from(c)); + items.push(Item::UNIT); + } + } + } + Ok(items.iter().fold((0, 0), |acc, item| add_widths(acc, item.width))) + } + + /// Handles an escape outside a class, port of `_escape`. + fn escape(&mut self, c: char) -> RunResult { + Ok(match c { + 'A' => self.push_at("\\A"), + 'b' => self.push_at("\\b"), + 'B' => self.push_at("\\B"), + // CPython's `\Z` is the end of the string; `fancy-regex`'s also allows trailing newlines. + 'z' | 'Z' => self.push_at("\\z"), + 'd' | 'D' | 's' | 'S' | 'w' | 'W' => { + self.out.push('\\'); + self.out.push(c); + Item::UNIT + } + '1'..='9' => return self.numbered_escape(c), + _ => { + let cp = match self.literal_escape(c, false)? { + Some(cp) => cp, + None if c == '0' => { + let digits = self.source.get_while(2, |d| d.is_digit(8))?; + u32::from_str_radix(&digits, 8).unwrap_or(0) + } + None if c.is_ascii_alphabetic() => return Err(self.source.error(format!("bad escape \\{c}"), 2)), + None => u32::from(c), + }; + push_literal(&mut self.out, cp); + Item::UNIT + } + }) + } + + /// `\1`-`\99`, a group reference, or a three-digit octal escape. + fn numbered_escape(&mut self, first: char) -> RunResult { + let mut digits = String::from(first); + if let Some(second) = self.source.next_char().filter(char::is_ascii_digit) { + self.source.advance()?; + digits.push(second); + let third = self.source.next_char().filter(|d| d.is_digit(8)); + if let Some(third) = third.filter(|_| first.is_digit(8) && second.is_digit(8)) { + self.source.advance()?; + digits.push(third); + let cp = u32::from_str_radix(&digits, 8).expect("three octal digits"); + if cp > 0o377 { + let msg = format!("octal escape value \\{digits} outside of range 0-0o377"); + return Err(self.source.error(msg, digits.len() + 1)); + } + push_literal(&mut self.out, cp); + return Ok(Item::UNIT); + } + } + let group: usize = digits.parse().expect("one or two digits"); + if group >= self.group_widths.len() { + return Err(self + .source + .error(format!("invalid group reference {group}"), digits.len())); + } + if self.group_widths[group].is_none() { + return Err(self.source.error("cannot refer to an open group", digits.len() + 1)); + } + self.check_lookbehind_group(group)?; + Ok(self.push_backref(group)) + } + + /// The escapes that mean the same character inside and outside a class. + /// + /// Returns `None` for an escape the caller handles itself. + fn literal_escape(&mut self, c: char, in_class: bool) -> RunResult> { + Ok(Some(match c { + 'a' => 0x07, + 'b' if in_class => 0x08, + 'f' => 0x0c, + 'n' => u32::from('\n'), + 'r' => u32::from('\r'), + 't' => u32::from('\t'), + 'v' => 0x0b, + '\\' => u32::from('\\'), + 'x' => self.hex_escape(c, 2)?, + 'u' => self.hex_escape(c, 4)?, + 'U' => self.hex_escape(c, 8)?, + 'N' => self.named_escape()?, + _ => return Ok(None), + })) + } + + /// `\xhh`, `\uhhhh` or `\Uhhhhhhhh`: exactly `digits` hex digits. + fn hex_escape(&mut self, c: char, digits: usize) -> RunResult { + let hex = self.source.get_while(digits, |d| d.is_ascii_hexdigit())?; + let escape = format!("\\{c}{hex}"); + if hex.len() != digits { + return Err(self.source.error(format!("incomplete escape {escape}"), escape.len())); + } + match u32::from_str_radix(&hex, 16) { + Ok(cp) if cp <= 0x10_FFFF => Ok(cp), + _ => Err(self.source.error(format!("bad escape {escape}"), escape.len())), + } + } + + /// `\N{NAME}`, a character by its Unicode name. + fn named_escape(&mut self) -> RunResult { + if !self.source.matches('{')? { + return Err(self.source.error("missing {", 0)); + } + let name = self.source.get_until('}', "character name")?; + if let Some(c) = unicode_names2::character(&name) { + Ok(u32::from(c)) + } else { + let msg = format!("undefined character name {}", StringRepr(&name)); + Err(self.source.error(msg, name.chars().count() + 4)) + } + } + + /// Handles a character class after its `[`, port of the class branch of `_parse`. + fn class(&mut self) -> RunResult<()> { + let here = self.source.tell() - 1; + let negate = self.source.matches('^')?; + let mut members: Vec = Vec::new(); + loop { + let Some(this) = self.source.get()? else { + return Err(self + .source + .error("unterminated character set", self.source.tell() - here)); + }; + if this == Token::Char(']') && !members.is_empty() { + break; + } + let first = self.class_member(this)?; + if !self.source.matches('-')? { + members.push(first); + continue; + } + let Some(that) = self.source.get()? else { + return Err(self + .source + .error("unterminated character set", self.source.tell() - here)); + }; + if that == Token::Char(']') { + members.push(first); + members.push(ClassItem::Literal(u32::from('-'))); + break; + } + let second = self.class_member(that)?; + match (first, second) { + (ClassItem::Literal(lo), ClassItem::Literal(hi)) if lo <= hi => members.push(ClassItem::Range(lo, hi)), + _ => { + let msg = format!("bad character range {this}-{that}"); + return Err(self.source.error(msg, this.len() + 1 + that.len())); + } + } + } + push_class(&mut self.out, negate, &members); + Ok(()) + } + + /// One class member from its first token, port of `_class_escape` for escapes. + fn class_member(&mut self, token: Token) -> RunResult { + let c = match token { + Token::Char(c) => return Ok(ClassItem::Literal(u32::from(c))), + Token::Escape(c) => c, + }; + if matches!(c, 'd' | 'D' | 's' | 'S' | 'w' | 'W') { + return Ok(ClassItem::Category(c)); + } + if let Some(cp) = self.literal_escape(c, true)? { + return Ok(ClassItem::Literal(cp)); + } + if c.is_digit(8) { + let digits = format!("{c}{}", self.source.get_while(2, |d| d.is_digit(8))?); + let cp = u32::from_str_radix(&digits, 8).expect("octal digits"); + return if cp > 0o377 { + let msg = format!("octal escape value \\{digits} outside of range 0-0o377"); + Err(self.source.error(msg, digits.len() + 1)) + } else { + Ok(ClassItem::Literal(cp)) + }; + } + if c.is_ascii_alphanumeric() { + Err(self.source.error(format!("bad escape \\{c}"), 2)) + } else { + Ok(ClassItem::Literal(u32::from(c))) + } + } + + /// Handles a quantifier, port of the repeat branch of `_parse`. + fn repeat(&mut self, this: char, items: &mut Vec) -> RunResult<()> { + let here = self.source.tell(); + let bounds = match this { + '?' => Some((0, 1)), + '*' => Some((0, MAXREPEAT)), + '+' => Some((1, MAXREPEAT)), + _ => self.brace_bounds(here)?, + }; + let Some((min, max)) = bounds else { + push_literal(&mut self.out, u32::from('{')); + items.push(Item::UNIT); + return Ok(()); + }; + let offset = self.source.tell() - here + 1; + let Some(item) = items.last_mut().filter(|item| item.kind != ItemKind::At) else { + return Err(self.source.error("nothing to repeat", offset)); + }; + if item.kind == ItemKind::Repeat { + return Err(self.source.error("multiple repeat", offset)); + } + self.out.push_str(&quantifier(min, max)); + if self.source.matches('?')? { + self.out.push('?'); + } else if self.source.matches('+')? { + self.out.push('+'); + } + let (lo, hi) = item.width; + let hi = if max == MAXREPEAT && hi != 0 { + MAXWIDTH + } else { + hi * u128::from(max) + }; + *item = Item { + kind: ItemKind::Repeat, + width: ((lo * u128::from(min)).min(MAXWIDTH), hi.min(MAXWIDTH)), + }; + Ok(()) + } + + /// Parses `{m,n}` after its `{`; `None` when the brace is a literal, with the position restored. + fn brace_bounds(&mut self, here: usize) -> RunResult> { + if self.source.next_char() == Some('}') { + return Ok(None); + } + let lo = self.source.get_while(usize::MAX, |c| c.is_ascii_digit())?; + let hi = if self.source.matches(',')? { + self.source.get_while(usize::MAX, |c| c.is_ascii_digit())? + } else { + lo.clone() + }; + if !self.source.matches('}')? { + self.source.seek(here)?; + return Ok(None); + } + let min = if lo.is_empty() { 0 } else { repeat_count(&lo)? }; + let max = if hi.is_empty() { MAXREPEAT } else { repeat_count(&hi)? }; + if max < min { + return Err(self + .source + .error("min repeat greater than max repeat", self.source.tell() - here)); + } + Ok(Some((min, max))) + } + + /// Emits a zero-width anchor. + fn push_at(&mut self, anchor: &str) -> Item { + self.out.push_str(anchor); + Item::AT + } + + /// Emits a reference to the closed group `group`; it matches what the group matched. + fn push_backref(&mut self, group: usize) -> Item { + write!(self.out, "\\k<{group}>").expect("writing to a String is infallible"); + Item { + kind: ItemKind::Other, + width: self.group_widths[group].expect("referenced group is closed"), + } + } + + /// True when `group` exists and has been closed. + fn is_closed(&self, group: usize) -> bool { + self.group_widths.get(group).is_some_and(Option::is_some) + } + + /// Rejects a reference from inside a lookbehind to an open group or one defined in that lookbehind. + fn check_lookbehind_group(&self, group: usize) -> RunResult<()> { + match self.lookbehind_groups { + Some(_) if !self.is_closed(group) => Err(self.source.error("cannot refer to an open group", 0)), + Some(first) if group >= first => Err(self + .source + .error("cannot refer to group defined in the same lookbehind subpattern", 0)), + _ => Ok(()), + } + } + + /// Numbers a new capturing group, rejecting a repeated name. + fn open_group(&mut self, name: Option<&str>) -> RunResult { + let group = self.group_widths.len(); + self.group_widths.push(None); + if let Some(name) = name { + if let Some(&previous) = self.group_names.get(name) { + let msg = format!( + "redefinition of group name {} as group {group}; was group {previous}", + StringRepr(name) + ); + return Err(self.source.error(msg, name.chars().count() + 1)); + } + self.group_names.insert(name.to_owned(), group); + } + Ok(group) + } + + /// Runs `parse` one group deeper, refusing nesting `fancy-regex` would reject. + fn nested(&mut self, start: usize, parse: impl FnOnce(&mut Self) -> RunResult) -> RunResult { + if self.depth + 1 >= MAX_NESTING { + return Err(self.source.error_at("pattern too deeply nested", start)); + } + self.depth += 1; + let result = parse(self); + self.depth -= 1; + result + } + + /// Handles a `(` construct, port of the group branch of `_parse`. + /// + /// `first` is true where global flags are allowed: the start of the first top-level branch. + fn group(&mut self, verbose: bool, nested: usize, first: bool) -> RunResult { + let start = self.source.tell() - 1; + if !self.source.matches('?')? { + let group = self.open_group(None)?; + self.out.push('('); + return self.group_body(start, verbose, nested, Some(group)); + } + let Some(token) = self.source.get()? else { + return Err(self.source.error("unexpected end of pattern", 0)); + }; + match token { + Token::Char('P') => self.python_extension(start, verbose, nested), + Token::Char(':') => { + self.out.push_str("(?:"); + self.group_body(start, verbose, nested, None) + } + Token::Char('#') => loop { + if self.source.next.is_none() { + let offset = self.source.tell() - start; + return Err(self.source.error("missing ), unterminated comment", offset)); + } + if self.source.get()? == Some(Token::Char(')')) { + return Ok(GroupOutcome::Nothing); + } + }, + Token::Char(c @ ('=' | '!' | '<')) => self.lookaround(c, start, verbose, nested), + Token::Char('(') => self.conditional(start, verbose, nested), + Token::Char('>') => { + self.out.push_str("(?>"); + self.group_body(start, verbose, nested, None) + } + Token::Char(c) if c == '-' || flag_bit(c).is_some() => self.flag_group(c, start, verbose, nested, first), + other => Err(self + .source + .error(format!("unknown extension ?{other}"), other.len() + 1)), + } + } + + /// Parses a group's contents and its `)`, after the opening has been emitted. + fn group_body( + &mut self, + start: usize, + verbose: bool, + nested: usize, + group: Option, + ) -> RunResult { + let width = self.nested(start, |this| this.parse_sub(verbose, nested + 1))?; + self.close(start)?; + if let Some(group) = group { + self.group_widths[group] = Some(width); + } + Ok(GroupOutcome::Item(Item { + kind: ItemKind::Other, + width, + })) + } + + /// Consumes and emits the `)` closing the construct opened at `start`. + fn close(&mut self, start: usize) -> RunResult<()> { + if self.source.matches(')')? { + self.out.push(')'); + Ok(()) + } else { + let offset = self.source.tell() - start; + Err(self.source.error("missing ), unterminated subpattern", offset)) + } + } + + /// `(?P...)` and `(?P=name)`. + fn python_extension(&mut self, start: usize, verbose: bool, nested: usize) -> RunResult { + if self.source.matches('<')? { + let name = self.source.get_until('>', "group name")?; + self.source.check_group_name(&name, 1)?; + let group = self.open_group(Some(&name))?; + write!(self.out, "(?P<{name}>").expect("writing to a String is infallible"); + self.group_body(start, verbose, nested, Some(group)) + } else if self.source.matches('=')? { + let name = self.source.get_until(')', "group name")?; + self.source.check_group_name(&name, 1)?; + let offset = name.chars().count() + 1; + let Some(&group) = self.group_names.get(&name) else { + let msg = format!("unknown group name {}", StringRepr(&name)); + return Err(self.source.error(msg, offset)); + }; + if !self.is_closed(group) { + return Err(self.source.error("cannot refer to an open group", offset)); + } + self.check_lookbehind_group(group)?; + Ok(GroupOutcome::Item(self.push_backref(group))) + } else { + match self.source.get()? { + None => Err(self.source.error("unexpected end of pattern", 0)), + Some(c) => Err(self.source.error(format!("unknown extension ?P{c}"), c.len() + 2)), + } + } + } + + /// Lookahead and lookbehind assertions, after `(?` and `c`. + fn lookaround(&mut self, c: char, start: usize, verbose: bool, nested: usize) -> RunResult { + let (behind, kind) = if c == '<' { + match self.source.get()? { + None => return Err(self.source.error("unexpected end of pattern", 0)), + Some(Token::Char(kind @ ('=' | '!'))) => (true, kind), + Some(other) => { + return Err(self + .source + .error(format!("unknown extension ?<{other}"), other.len() + 2)); + } + } + } else { + (false, c) + }; + let outermost = behind && self.lookbehind_groups.is_none(); + if outermost { + self.lookbehind_groups = Some(self.group_widths.len()); + } + self.out.push_str(match (behind, kind) { + (false, '=') => "(?=", + (false, _) => "(?!", + (true, '=') => "(?<=", + (true, _) => "(? MAXCODE { + "looks too much behind" + } else if lo != hi { + "look-behind requires fixed-width pattern" + } else { + return; + }; + if self.lookbehind_error.is_none_or(|(first, _)| start < first) { + self.lookbehind_error = Some((start, msg)); + } + } + + /// `(?(group)yes|no)`, after `(?(`. + fn conditional(&mut self, start: usize, verbose: bool, nested: usize) -> RunResult { + let name = self.source.get_until(')', "group name")?; + let offset = name.chars().count() + 1; + let group = if name.bytes().all(|b| b.is_ascii_digit()) { + let number = name.parse::().unwrap_or(u64::MAX); + if number == 0 { + return Err(self.source.error("bad group number", offset)); + } + if number >= MAXGROUPS { + let msg = format!("invalid group reference {}", name.trim_start_matches('0')); + return Err(self.source.error(msg, offset)); + } + // Repeats are kept rather than searched for: `finish` reports the first entry, so this matches + // CPython's first-position dict without making many conditionals quadratic. + self.groupref_pos.push((number, self.source.tell() - offset)); + usize::try_from(number).expect("below MAXGROUPS") + } else { + self.source.check_group_name(&name, 1)?; + let Some(&group) = self.group_names.get(&name) else { + let msg = format!("unknown group name {}", StringRepr(&name)); + return Err(self.source.error(msg, offset)); + }; + group + }; + self.check_lookbehind_group(group)?; + write!(self.out, "(?({group})").expect("writing to a String is infallible"); + let (yes, no) = self.nested(start, |this| { + let yes = this.parse(verbose, nested + 1, false)?; + if !this.source.matches('|')? { + return Ok((yes, None)); + } + this.out.push('|'); + let no = this.parse(verbose, nested + 1, false)?; + if this.source.next == Some(Token::Char('|')) { + return Err(this.source.error("conditional backref with more than two branches", 0)); + } + Ok((yes, Some(no))) + })?; + self.close(start)?; + let width = match no { + Some(no) => (yes.0.min(no.0), yes.1.max(no.1)), + None => (0, yes.1), + }; + Ok(GroupOutcome::Item(Item { + kind: ItemKind::Other, + width, + })) + } + + /// Inline flags, global `(?flags)` or scoped `(?flags-flags:...)`, after `(?`. + fn flag_group( + &mut self, + c: char, + start: usize, + verbose: bool, + nested: usize, + first: bool, + ) -> RunResult { + match self.parse_flags(c)? { + None => { + if !first { + let offset = self.source.tell() - start; + return Err(self + .source + .error("global flags not at the start of the expression", offset)); + } + Ok(GroupOutcome::GlobalFlags) + } + Some((add, del)) => { + let (on, off) = (flag_letters(add), flag_letters(del)); + self.out.push_str("(?"); + self.out.push_str(&on); + if !off.is_empty() { + self.out.push('-'); + self.out.push_str(&off); + } + self.out.push(':'); + let verbose = (verbose || add & VERBOSE != 0) && del & VERBOSE == 0; + self.group_body(start, verbose, nested, None) + } + } + } + + /// Port of `_parse_flags`: `None` for global flags, which it applies and emits, else the scoped flags. + fn parse_flags(&mut self, first: char) -> RunResult> { + let mut add = 0; + let mut current = Token::Char(first); + if first != '-' { + loop { + let c = current.char(); + if c == 'L' { + return Err(self + .source + .error("bad inline flags: cannot use 'L' flag with a str pattern", 0)); + } + let flag = flag_bit(c).expect("checked to be a flag"); + add |= flag; + if flag & TYPE_FLAGS != 0 && add & TYPE_FLAGS != flag { + return Err(self + .source + .error("bad inline flags: flags 'a', 'u' and 'L' are incompatible", 0)); + } + let Some(next) = self.source.get()? else { + return Err(self.source.error("missing -, : or )", 0)); + }; + current = next; + if matches!(next, Token::Char(')' | '-' | ':')) { + break; + } + if !is_flag(next) { + let msg = if is_alpha(next) { + "unknown flag" + } else { + "missing -, : or )" + }; + return Err(self.source.error(msg, next.len())); + } + } + } + if current == Token::Char(')') { + self.flags |= add; + let letters = flag_letters(add); + if !letters.is_empty() { + write!(self.out, "(?{letters})").expect("writing to a String is infallible"); + } + return Ok(None); + } + let mut del = 0; + if current == Token::Char('-') { + let Some(mut next) = self.source.get()? else { + return Err(self.source.error("missing flag", 0)); + }; + if !is_flag(next) { + let msg = if is_alpha(next) { "unknown flag" } else { "missing flag" }; + return Err(self.source.error(msg, next.len())); + } + loop { + let flag = flag_bit(next.char()).expect("checked to be a flag"); + if flag & TYPE_FLAGS != 0 { + return Err(self + .source + .error("bad inline flags: cannot turn off flags 'a', 'u' and 'L'", 0)); + } + del |= flag; + let Some(after) = self.source.get()? else { + return Err(self.source.error("missing :", 0)); + }; + if after == Token::Char(':') { + break; + } + if !is_flag(after) { + let msg = if is_alpha(after) { "unknown flag" } else { "missing :" }; + return Err(self.source.error(msg, after.len())); + } + next = after; + } + } + if add & del != 0 { + return Err(self.source.error("bad inline flags: flag turned on and off", 1)); + } + Ok(Some((add, del))) + } +} + +/// The `re` flag bit for an inline flag letter. +fn flag_bit(c: char) -> Option { + match c { + 'i' => Some(IGNORECASE), + 'L' => Some(LOCALE), + 'm' => Some(MULTILINE), + 's' => Some(DOTALL), + 'x' => Some(VERBOSE), + 'a' => Some(ASCII), + 'u' => Some(UNICODE), + _ => None, + } +} + +/// True for a plain character that is an inline flag letter. +fn is_flag(token: Token) -> bool { + matches!(token, Token::Char(c) if flag_bit(c).is_some()) +} + +/// Python's `str.isalpha()` on the token's text. +fn is_alpha(token: Token) -> bool { + matches!(token, Token::Char(c) if c.is_alphabetic()) +} + +/// The `fancy-regex` letters for `flags`: only `i`, `m` and `s` change how the output matches. +fn flag_letters(flags: u16) -> String { + [(IGNORECASE, 'i'), (MULTILINE, 'm'), (DOTALL, 's')] + .into_iter() + .filter(|&(bit, _)| flags & bit != 0) + .map(|(_, letter)| letter) + .collect() +} + +/// A repeat count, which must be below [`MAXREPEAT`]. +fn repeat_count(digits: &str) -> RunResult { + digits + .parse::() + .ok() + .filter(|&n| n < MAXREPEAT) + .ok_or_else(|| ExcType::overflow_error("the repetition number is too large")) +} + +/// Appends `c` as a literal, in a form `fancy-regex` cannot read as syntax. +fn push_literal(out: &mut String, cp: u32) { + match char::from_u32(cp) { + Some(c) if c.is_ascii_alphanumeric() || c == '_' || !c.is_ascii() => out.push(c), + Some(c) => push_hex(out, c), + // A surrogate: no Monty string contains one, so the literal never matches. + None => out.push_str("[^\\s\\S]"), + } +} + +/// Appends `\x{..}` for `c`. +fn push_hex(out: &mut String, c: char) { + write!(out, "\\x{{{:x}}}", u32::from(c)).expect("writing to a String is infallible"); +} + +/// Appends a character class; surrogates are dropped, since no Monty string contains one. +fn push_class(out: &mut String, negate: bool, members: &[ClassItem]) { + let mut body = String::new(); + for &member in members { + match member { + ClassItem::Literal(cp) => { + if let Some(c) = char::from_u32(cp) { + push_class_char(&mut body, c); + } + } + ClassItem::Range(lo, hi) => { + let lo = if (0xD800..=0xDFFF).contains(&lo) { 0xE000 } else { lo }; + let hi = if (0xD800..=0xDFFF).contains(&hi) { 0xD7FF } else { hi }; + if let (Some(lo), Some(hi)) = (char::from_u32(lo), char::from_u32(hi)) + && lo <= hi + { + push_class_char(&mut body, lo); + body.push('-'); + push_class_char(&mut body, hi); + } + } + ClassItem::Category(c) => { + body.push('\\'); + body.push(c); + } + } + } + match (body.is_empty(), negate) { + // Only surrogates: the class matches nothing, or anything when negated. + (true, false) => out.push_str("[^\\s\\S]"), + (true, true) => out.push_str("[\\s\\S]"), + (false, _) => { + out.push('['); + if negate { + out.push('^'); + } + out.push_str(&body); + out.push(']'); + } + } +} + +/// Appends a class member character, escaping the punctuation `fancy-regex` treats as class syntax. +fn push_class_char(out: &mut String, c: char) { + if c.is_ascii_alphanumeric() || c == '_' || !c.is_ascii() { + out.push(c); + } else { + push_hex(out, c); + } +} + +/// The quantifier for `{min,max}`, using the short forms where they apply. +fn quantifier(min: u64, max: u64) -> String { + match (min, max) { + (0, MAXREPEAT) => "*".to_owned(), + (1, MAXREPEAT) => "+".to_owned(), + (0, 1) => "?".to_owned(), + (min, MAXREPEAT) => format!("{{{min},}}"), + (min, max) if min == max => format!("{{{min}}}"), + (min, max) => format!("{{{min},{max}}}"), + } +} + +/// Adds two widths, saturating at [`MAXWIDTH`]. +fn add_widths(a: Width, b: Width) -> Width { + ((a.0 + b.0).min(MAXWIDTH), (a.1 + b.1).min(MAXWIDTH)) +} diff --git a/crates/bashkit-monty/src/types/set.rs b/crates/bashkit-monty/src/types/set.rs index 60bed790d..cbbf68410 100644 --- a/crates/bashkit-monty/src/types/set.rs +++ b/crates/bashkit-monty/src/types/set.rs @@ -186,7 +186,11 @@ impl<'h> HeapReadMut<'h, SetStorage> { /// Returns `Err` if the key is unhashable. fn remove(&self, value: &Value, vm: &mut VM<'h>) -> RunResult { let hash = set_element_hash(value, vm)?; + self.remove_with_hash(value, hash, vm) + } + /// Set-to-set mutation reuses the hash cached by the source entry. + fn remove_with_hash(&self, value: &Value, hash: u64, vm: &mut VM<'h>) -> RunResult { let Some(slot) = self.find_index(value, hash, vm)? else { return Ok(false); }; @@ -838,6 +842,53 @@ fn clone_storage_checked(storage: &SetStorage, vm: &VM<'_>) -> RunResult HeapObjectRead<'h, Set> { + /// Mutates for sets/frozensets; dict views and other operands use binary/reflected fallback. + /// Snapshots distinct right operands and reuses cached hashes during mutation. + fn inplace_algebra(&self, other: &Value, op: SetAlgebra, vm: &mut VM<'h>) -> RunResult { + let Some(id) = other.ref_id() else { + return Ok(false); + }; + let other_storage = match vm.heap.get(id) { + HeapData::Set(set) => &set.0, + HeapData::FrozenSet(set) => &set.storage, + _ => return Ok(false), + }; + + // CPython's self-operations bypass element equality; probing a copy could invoke it. + if id == self.id() { + if matches!(op, SetAlgebra::Difference | SetAlgebra::SymmetricDifference) { + self.clear(vm); + } + return Ok(true); + } + + let storage = clone_storage_checked(other_storage, vm)?; + defer_drop!(storage, vm); + // Equality callbacks may clear the source and collect cycles; keep snapshot members rooted. + let storage = vm.heap.protect(storage); + + if matches!(op, SetAlgebra::Intersection) { + // Intersection builds a separate table; swap storage so aliases keep the receiver. + let result = self.storage().intersection(&storage, vm)?; + let old = mem::replace(&mut self.get_mut(vm.heap).0, result); + old.drop_with(vm); + } else { + // These operators mutate incrementally, retaining earlier updates if a comparison raises. + let iter = storage.iter(vm)?; + defer_drop_mut!(iter, vm); + while let Some((value, hash)) = iter.next_entry(vm)? { + let removed = + !matches!(op, SetAlgebra::Union) && self.storage_mut().remove_with_hash(value, hash, vm)?; + if matches!(op, SetAlgebra::Union) || matches!(op, SetAlgebra::SymmetricDifference) && !removed { + self.add_with_hash(value.clone_with_heap(vm.heap), hash, vm)?; + } + } + } + Ok(true) + } +} + impl<'h> HeapReadMut<'h, Set> { /// Adds an element to the set, transferring ownership. /// @@ -1204,6 +1255,22 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Set> { Ok(Some(Value::Ref(result_id))) } + fn py_isub_impl(&mut self, other: &Value, vm: &mut VM<'h>) -> RunResult { + self.inplace_algebra(other, SetAlgebra::Difference, vm) + } + + fn py_iand_impl(&mut self, other: &Value, vm: &mut VM<'h>) -> RunResult { + self.inplace_algebra(other, SetAlgebra::Intersection, vm) + } + + fn py_ior_impl(&mut self, other: &Value, vm: &mut VM<'h>) -> RunResult { + self.inplace_algebra(other, SetAlgebra::Union, vm) + } + + fn py_ixor_impl(&mut self, other: &Value, vm: &mut VM<'h>) -> RunResult { + self.inplace_algebra(other, SetAlgebra::SymmetricDifference, vm) + } + fn py_repr_fmt(&self, f: &mut impl Write, vm: &mut VM<'h>, heap_ids: &mut LazyHeapSet) -> RunResult<()> { self.storage().repr_fmt(f, vm, heap_ids, "set") } @@ -1796,7 +1863,7 @@ pub(crate) fn set_element_hash(value: &Value, vm: &mut VM<'_>) -> RunResult } /// Finds the nested value responsible for a tuple-like element being unhashable. -fn unhashable_type_name(value: &Value, vm: &mut VM<'_>) -> RunResult { +pub(crate) fn unhashable_type_name(value: &Value, vm: &mut VM<'_>) -> RunResult { let Value::Ref(id) = value else { return Ok(value.py_type_name(vm).into_owned()); }; diff --git a/crates/bashkit-monty/src/types/slice.rs b/crates/bashkit-monty/src/types/slice.rs index 0f4c05695..1cf2c58d0 100644 --- a/crates/bashkit-monty/src/types/slice.rs +++ b/crates/bashkit-monty/src/types/slice.rs @@ -166,6 +166,38 @@ pub(crate) fn optional_sequence_bound(value: &Value, default: usize, len: usize, Ok(bound.map_or(default, |i| normalize_sequence_index(i, len))) } +/// The `(start, end)` range of a `str` or `bytes` search, or `None` for a +/// `start` past `end`, where nothing is found — see [`search_range`]. +pub(crate) type SearchRange = Option<(usize, usize)>; + +/// The optional `start` and `end` of a `str` or `bytes` search, adjusted as +/// CPython's `ADJUST_INDICES` does: both are converted like +/// [`optional_sequence_bound`] and clamped at zero, and `end` at `len`. +/// +/// `start` is not clamped at `len`, so a `start` past `end` stays apart from an +/// empty range at the end. That range is `None`: CPython finds nothing there, +/// not even the empty string, where the empty slice `s[start:end]` would match +/// it (`'abc'.find('', 4)` is `-1`, `'abc'.count('', 2, 1)` is `0`). +pub(crate) fn search_range( + start: Option<&Value>, + end: Option<&Value>, + len: usize, + vm: &mut VM<'_>, +) -> RunResult { + let start = match start { + Some(value) => match value_to_option_i64(value, vm)?.unwrap_or(0) { + index if index < 0 => normalize_sequence_index(index, len), + index => usize::try_from(index).unwrap_or(usize::MAX), + }, + None => 0, + }; + let end = match end { + Some(value) => optional_sequence_bound(value, len, len, vm)?, + None => len, + }; + Ok((start <= end).then_some((start, end))) +} + /// CPython's `_PyEval_SliceIndex`: an `int`, or the `__index__` of an object /// that has one, **saturated** to `i64` rather than raised on. `Ok(None)` means /// the value is not `__index__`-able, leaving the `TypeError` to the caller, diff --git a/crates/bashkit-monty/src/types/str.rs b/crates/bashkit-monty/src/types/str.rs index 54f4f7904..c325302df 100644 --- a/crates/bashkit-monty/src/types/str.rs +++ b/crates/bashkit-monty/src/types/str.rs @@ -1,4 +1,4 @@ -use std::{cell::Cell, fmt::Write, ops}; +use std::{cell::Cell, fmt::Write, ops, str}; use monty_types::{ResourceError, ResourceTracker}; pub use monty_types::{StringRepr, string_repr_fmt}; @@ -6,6 +6,7 @@ use smallvec::smallvec; use super::{ Bytes, CmpOrder, PyTrait, + inline_str::InlineStr, unicode_type::{casefold, is_space, lowercase, type_record, uppercase}, unicode_type_data::TypeRecord, }; @@ -16,25 +17,25 @@ use crate::{ defer_drop, exception_private::{ExcType, ExcTypeExt, RunResult}, hash::{HashValue, hash_python_str}, - heap::{DropWithContext, Heap, HeapData, HeapId, HeapItem, HeapObjectRead, HeapView, heap_read_ref_as_field}, + heap::{ + DropGuard, DropWithContext, Heap, HeapData, HeapId, HeapItem, HeapObjectRead, HeapReader, HeapView, + heap_read_ref_as_field, + }, identity::Identity, intern::{Interns, StaticStrings, StringId}, percent_format::percent_format, - resource_checks::{check_repeat_size, check_replace_size}, + resource_checks::{check_repeat_size, check_replace_size, collect_checked, push_checked, repeated_len}, str_format::str_format, string_builder::StringBuilder, types::{ LazyHeapSet, Type, - long_int::repeat_count, py_trait::PyObjectIdentity, - slice::{optional_sequence_bound, slice_collect_iterator}, + slice::{SearchRange, search_range, slice_collect_iterator}, }, - value::{EitherStr, Value, eq_str}, + value::{EitherStr, VALUE_SIZE, Value, eq_str}, }; -/// Python string value stored on the heap. -/// -/// Wraps a Rust `String` and provides Python-compatible operations. +/// Heap-backed Python string with cached hash and ASCII status. /// `len()` returns the number of Unicode codepoints (characters), matching Python semantics. /// /// Caches its Python hash and whether it is ASCII, both computed on first use and @@ -119,12 +120,13 @@ impl Str { // A missing object wins over the decoding args: `str(encoding='utf-8')` is ''. return Ok(Value::InternString(StringId::EMPTY)); }; + if object.is_str(vm.heap) { + return Err(ExcType::type_error_decoding_str_not_supported()); + } let bytes: &[u8] = match object { Value::InternBytes(bytes_id) => vm.interns.get_bytes(*bytes_id), - Value::InternString(_) => return Err(ExcType::type_error_decoding_str_not_supported()), Value::Ref(heap_id) => match vm.heap.get(*heap_id) { HeapData::Bytes(b) => b.as_slice(), - HeapData::Str(_) => return Err(ExcType::type_error_decoding_str_not_supported()), _ => return Err(ExcType::type_error_decoding_need_bytes(object.py_type_name(vm))), }, _ => return Err(ExcType::type_error_decoding_need_bytes(object.py_type_name(vm))), @@ -137,20 +139,28 @@ impl Str { } } -/// An allocation-free string view that retains interned or heap identity. +/// A string view that preserves Python identity. /// /// Heap reads keep the receiver available across calls such as `__index__` without /// holding a Rust borrow of its text during Python execution. pub(crate) enum PyStr<'h> { Interned(StringId), + Inline(InlineStr), Heap(HeapObjectRead<'h, Str>), } +impl<'a> HeapView<'a, str> for InlineStr { + fn get<'r>(&'r self, _reader: &'r HeapReader<'a>) -> &'r str { + self.as_str() + } +} + impl<'h> PyStr<'h> { /// Extracts a string without copying its contents. pub(crate) fn from_value(value: &Value, vm: &VM<'h>) -> Option { match value { Value::InternString(id) => Some(Self::Interned(*id)), + Value::InlineString(text) => Some(Self::Inline(*text)), Value::Ref(id) => vm.heap.read_as(*id).map(Self::Heap), _ => None, } @@ -160,6 +170,7 @@ impl<'h> PyStr<'h> { pub(crate) fn as_str<'a>(&'a self, vm: &'a VM<'h>) -> &'a str { match self { Self::Interned(id) => vm.interns.get_str(*id), + Self::Inline(text) => text.as_str(), Self::Heap(value) => value.get(vm.heap).as_str(), } } @@ -169,6 +180,7 @@ impl PyObjectIdentity for PyStr<'_> { fn py_identity(&self) -> Identity { match self { Self::Interned(id) => Identity::InternString(id.index()), + Self::Inline(text) => Identity::InlineString(*text), Self::Heap(value) => value.py_identity(), } } @@ -182,6 +194,7 @@ impl<'h> PyTrait<'h> for PyStr<'h> { fn py_eq_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { match self { Self::Interned(id) => Value::InternString(*id).py_eq_impl(other, vm), + Self::Inline(text) => Ok(text.eq_value(other, vm)), Self::Heap(value) => value.py_eq_impl(other, vm), } } @@ -189,13 +202,22 @@ impl<'h> PyTrait<'h> for PyStr<'h> { fn py_str(&self, vm: &mut VM<'h>) -> RunResult { Ok(match self { Self::Interned(id) => Value::InternString(*id), + Self::Inline(text) => Value::InlineString(*text), Self::Heap(value) => value.clone_value(vm.heap), }) } fn py_len(&self, vm: &VM<'h>) -> Option { match self { - Self::Interned(id) => Some(vm.interns.get_str(*id).chars().count()), + Self::Interned(id) => { + let text = vm.interns.get_str(*id); + Some(if vm.interns.str_is_ascii(*id) { + text.len() + } else { + text.chars().count() + }) + } + Self::Inline(text) => Some(text.as_str().chars().count()), Self::Heap(value) => value.py_len(vm), } } @@ -213,7 +235,10 @@ impl<'h> PyTrait<'h> for PyStr<'h> { } fn py_mul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { - repeat_str(self.as_str(vm), other, vm) + let Some(count) = other.py_value(vm).repeat_count(vm)? else { + return Ok(None); + }; + repeat_str(self.as_str(vm), count, vm) } fn py_rmul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { @@ -228,8 +253,9 @@ impl<'h> PyTrait<'h> for PyStr<'h> { match self { Self::Interned(id) => { let text = vm.interns.get_str(*id); - str_getitem(&*vm.heap.protect(text), text.is_ascii(), key, vm) + str_getitem(&*vm.heap.protect(text), vm.interns.str_is_ascii(*id), key, vm) } + Self::Inline(text) => str_getitem(text, text.as_bytes().is_ascii(), key, vm), Self::Heap(value) => value.py_getitem(key, vm), } } @@ -249,6 +275,13 @@ impl<'h> PyTrait<'h> for PyStr<'h> { let text = vm.heap.protect(vm.interns.get_str(*id)); call_str_method_impl(&*text, method, args, vm).map(CallResult::Value) } + Self::Inline(text) => { + let Some(method) = attr.static_string(vm.interns) else { + args.drop_with(vm); + return Err(ExcType::attribute_error(Type::Str, attr.as_str(vm.interns))); + }; + call_str_method_impl(text, method, args, vm).map(CallResult::Value) + } Self::Heap(value) => value.py_call_attr(vm, attr, args), } } @@ -291,55 +324,65 @@ fn str_ctor_arg_check(arg: Option<&Value>, name: &str, vm: &VM<'_>) -> RunResult fn ctor_str_arg<'a>(arg: Option<&'a Value>, default: &'a str, vm: &'a VM<'_>) -> RunResult<&'a str> { match arg { None => Ok(default), - Some(v) => v.to_str(vm), + Some(v) => v.try_to_str(vm), } } -/// Allocates a string, reusing reserved IDs for empty strings and ASCII characters. -/// Other strings are heap-allocated without consulting the executor interner. -/// Owned buffers move into heap storage; borrowed text is copied only when needed. +/// Creates a string value, reusing reserved IDs for empty strings and ASCII characters. +/// Moves owned text into storage when possible. pub fn allocate_string(s: impl AsRef + Into>, heap: &Heap) -> Value { let bytes = s.as_ref().as_bytes(); match bytes.len() { 0 => Value::InternString(StringId::EMPTY), 1 => Value::InternString(StringId::from_ascii(bytes[0])), - _ => allocate_string_no_interning(s, heap), + 2..=15 => Value::InlineString(InlineStr::new(s.as_ref()).expect("length checked above")), + _ => allocate_string_on_heap(s, heap), } } -/// Allocates a string directly on the heap, skipping the intern check. -/// -/// Use this only when the caller can guarantee the string is longer than one -/// byte (e.g. always contains a fixed prefix like `"0x"`, `"0o"`, or a -/// formatted date). For inputs of unknown length, use [`allocate_string`]. -/// -/// Accepts `impl Into>` for the same reasons as [`allocate_string`]. -pub fn allocate_string_no_interning(s: impl Into>, heap: &Heap) -> Value { - let heap_id = heap.allocate(HeapData::Str(Str::new(s))); - Value::Ref(heap_id) +/// Creates a string value without checking for reserved string IDs. +/// The caller must know the text is longer than one byte; otherwise use [`allocate_string`]. +pub fn allocate_string_no_interning(s: impl AsRef + Into>, heap: &Heap) -> Value { + if (2..=15).contains(&s.as_ref().len()) { + return Value::InlineString(InlineStr::new(s.as_ref()).expect("length checked above")); + } + allocate_string_on_heap(s, heap) } -/// Converts a native integer count and preflights the repeated string allocation. -fn repeat_str(value: &str, count: &Value, vm: &VM<'_>) -> RunResult> { - let Some(count) = repeat_count(count, vm)? else { - return Ok(None); - }; - check_repeat_size(value.len(), count, &vm.heap.tracker)?; - Ok(Some(allocate_string(value.repeat(count), vm.heap))) +/// Forces heap storage even for short strings. +pub fn allocate_string_on_heap(s: impl Into>, heap: &Heap) -> Value { + Value::Ref(heap.allocate(HeapData::Str(Str::new(s.into())))) } -/// Allocates a single character as a string value. +/// Preflights the repeated string allocation. /// -/// ASCII characters use pre-interned strings for efficiency. -/// Non-ASCII characters are allocated on the heap. -/// -/// This is used by string iteration and `chr()` builtin. -pub fn allocate_char(c: char, heap: &Heap) -> Value { +/// Raises CPython's `OverflowError` past `isize::MAX` bytes and `MemoryError` when the +/// allocator refuses, where `str::repeat` would panic or abort with no memory limit set. +fn repeat_str(value: &str, count: usize, vm: &VM<'_>) -> RunResult> { + let total = repeated_len(value.len(), count, 1).map_err(|_| ExcType::repeated_string_too_long())?; + check_repeat_size(value.len(), count, &vm.heap.tracker)?; + let mut repeated = String::new(); + repeated + .try_reserve_exact(total) + .map_err(|_| ExcType::allocation_too_large())?; + if total > 0 { + // Doubling copies: each pass appends a whole number of copies, so every cut is a char boundary. + repeated.push_str(value); + while repeated.len() < total { + repeated.extend_from_within(..repeated.len().min(total - repeated.len())); + } + } + Ok(Some(allocate_string(repeated, vm.heap))) +} + +/// Creates a single-character string without allocating. +pub fn allocate_char(c: char) -> Value { if c.is_ascii() { Value::InternString(StringId::from_ascii(c as u8)) } else { - let heap_id = heap.allocate(HeapData::Str(Str::new(c.to_string()))); - Value::Ref(heap_id) + let mut bytes = [0; 4]; + let text = c.encode_utf8(&mut bytes); + Value::InlineString(InlineStr::new(text).expect("a UTF-8 character fits inline")) } } @@ -365,19 +408,22 @@ pub(crate) fn concat_allocate_str(a: &str, b: &str, heap: &Heap) -> Result Option { - let char_count = if ascii { s.len() } else { s.chars().count() }; - let len = i64::try_from(char_count).ok()?; - let normalized = if index < 0 { index + len } else { index }; - - if normalized < 0 || normalized >= len { - return None; - } - - let idx = usize::try_from(normalized).ok()?; if ascii { - Some(char::from(s.as_bytes()[idx])) + let offset = if index < 0 { + s.len().checked_sub(usize::try_from(index.unsigned_abs()).ok()?)? + } else { + usize::try_from(index).ok()? + }; + s.as_bytes().get(offset).copied().map(char::from) + } else if index == -1 { + s.chars().next_back() + } else if index < 0 { + // Forward skipping is faster than reverse traversal for distant offsets. + let length = s.chars().count(); + let offset = usize::try_from(index.unsigned_abs()).ok()?; + s.chars().nth(length.checked_sub(offset)?) } else { - s.chars().nth(idx) + s.chars().nth(usize::try_from(index).ok()?) } } @@ -407,7 +453,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Str> { fn py_iter(&self, vm: &mut VM<'h>) -> RunResult { Ok(CallResult::Value(StringIterator::from_heap( self.id(), - self.get(vm.heap).as_str().is_ascii(), + self.get(vm.heap).is_ascii(), vm, ))) } @@ -460,14 +506,6 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Str> { str_add(self.get(vm.heap).as_str(), other, vm) } - fn py_mul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { - repeat_str(self.get(vm.heap).as_str(), other, vm) - } - - fn py_rmul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { - self.py_mul_impl(other, vm) - } - /// `str % args` is printf-style formatting, see `percent_format`. fn py_mod_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { let template = copy_format_template(self.get(vm.heap).as_str(), &vm.heap.tracker)?; @@ -502,6 +540,22 @@ fn str_getitem<'h>(s: &impl HeapView<'h, str>, ascii: bool, key: &Value, vm: &mu && let HeapData::Slice(slice) = vm.heap.get(*id) { let text = s.get(vm.heap); + if slice.step.unwrap_or(1) == 1 { + let length = if ascii { text.len() } else { text.chars().count() }; + let (start, stop, _) = slice.indices(length)?; + if start >= stop { + return Ok(allocate_string("", vm.heap)); + } + let start = usize::try_from(start).expect("normalized slice start"); + let stop = usize::try_from(stop).expect("normalized slice stop"); + let result = if ascii { + &text[start..stop] + } else { + slice_string(text, start, stop) + }; + // Contiguous slices copy UTF-8 directly, without collecting characters. + return Ok(allocate_string(result, vm.heap)); + } let result: Box = if ascii { // Byte iterators count and skip in O(1), unlike `chars()`. slice_collect_iterator(vm, slice, text.bytes(), char::from)? @@ -512,7 +566,7 @@ fn str_getitem<'h>(s: &impl HeapView<'h, str>, ascii: bool, key: &Value, vm: &mu } else { let index = key.as_index(vm, Type::Str)?; let c = get_char_at_index(s.get(vm.heap), ascii, index).ok_or_else(ExcType::str_index_error)?; - Ok(allocate_char(c, vm.heap)) + Ok(allocate_char(c)) } } @@ -676,19 +730,7 @@ fn call_str_method_impl<'h>( } } -/// Implements Python's `str.join(iterable)` method. -/// -/// Joins elements of the iterable with the separator string, returning -/// a new heap-allocated string. Each element must be a string. -/// -/// # Arguments -/// * `separator` - The separator string (e.g., "," for comma-separated) -/// * `iterable` - The iterable containing string elements to join -/// * `heap` - The heap for allocation and reference counting -/// * `interns` - The interns table for resolving interned strings -/// -/// # Errors -/// Returns `TypeError` if the argument is not iterable or if any element is not a string. +/// Joins an iterable of strings with the separator, rejecting non-string elements. fn str_join<'h>(separator: &impl HeapView<'h, str>, iterable: Value, vm: &mut VM<'h>) -> RunResult { // Checked up front: a user `__iter__` can raise anything, and rewriting that // as "can only join an iterable" would hide it, resource errors included. @@ -710,23 +752,12 @@ fn str_join<'h>(separator: &impl HeapView<'h, str>, iterable: Value, vm: &mut VM result.push_str(separator.get(vm.heap)); } - // Check item is a string and extract its content - match item { - Value::InternString(id) => { - result.push_str(vm.interns.get_str(*id)); - } - Value::Ref(heap_id) => { - if let HeapData::Str(s) = vm.heap.get(*heap_id) { - result.push_str(s.as_str()); - } else { - let t = item.py_type_name(vm); - return Err(ExcType::type_error_join_item(index, &t)); - } - } - _ => { - let t = item.py_type_name(vm); - return Err(ExcType::type_error_join_item(index, &t)); - } + // `as_str` borrows interned, inline, and heap-backed strings without copying. + if let Some(text) = item.as_str(vm) { + result.push_str(text); + } else { + let t = item.py_type_name(vm); + return Err(ExcType::type_error_join_item(index, &t)); } index += 1; } @@ -916,8 +947,11 @@ fn str_isdecimal(s: &str) -> bool { /// Returns the lowest index in the string where substring sub is found within /// the slice s[start:end]. Returns -1 if sub is not found. fn str_find<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { - let str_len = s.get(vm.heap).chars().count(); - let (sub, start, end) = parse_search_args("str.find", str_len, args, vm)?; + let (sub, range) = parse_search_args("str.find", s, args, vm)?; + let Some((start, end)) = range else { + // `start` past `end` finds nothing: `'abc'.find('', 4) == -1` + return Ok(Value::Int(-1)); + }; let s = s.get(vm.heap); let slice = slice_string(s, start, end); let result = match slice.find(&sub) { @@ -936,8 +970,11 @@ fn str_find<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) -> /// Returns the highest index in the string where substring sub is found within /// the slice s[start:end]. Returns -1 if sub is not found. fn str_rfind<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { - let str_len = s.get(vm.heap).chars().count(); - let (sub, start, end) = parse_search_args("str.rfind", str_len, args, vm)?; + let (sub, range) = parse_search_args("str.rfind", s, args, vm)?; + let Some((start, end)) = range else { + // `start` past `end` finds nothing: `'abc'.rfind('', 4) == -1` + return Ok(Value::Int(-1)); + }; let s = s.get(vm.heap); let slice = slice_string(s, start, end); let result = match slice.rfind(&sub) { @@ -955,8 +992,11 @@ fn str_rfind<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) - /// /// Like find(), but raises ValueError when the substring is not found. fn str_index<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { - let str_len = s.get(vm.heap).chars().count(); - let (sub, start, end) = parse_search_args("str.index", str_len, args, vm)?; + let (sub, range) = parse_search_args("str.index", s, args, vm)?; + let Some((start, end)) = range else { + // `start` past `end` finds nothing: `'abc'.index('', 4)` raises `ValueError` + return Err(ExcType::value_error_substring_not_found()); + }; let s = s.get(vm.heap); let slice = slice_string(s, start, end); match slice.find(&sub) { @@ -973,8 +1013,11 @@ fn str_index<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) - /// /// Like rfind(), but raises ValueError when the substring is not found. fn str_rindex<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { - let str_len = s.get(vm.heap).chars().count(); - let (sub, start, end) = parse_search_args("str.rindex", str_len, args, vm)?; + let (sub, range) = parse_search_args("str.rindex", s, args, vm)?; + let Some((start, end)) = range else { + // `start` past `end` finds nothing: `'abc'.rindex('', 4)` raises `ValueError` + return Err(ExcType::value_error_substring_not_found()); + }; let s = s.get(vm.heap); let slice = slice_string(s, start, end); match slice.rfind(&sub) { @@ -992,8 +1035,11 @@ fn str_rindex<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) /// Returns the number of non-overlapping occurrences of substring sub in /// the string s[start:end]. fn str_count<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { - let str_len = s.get(vm.heap).chars().count(); - let (sub, start, end) = parse_search_args("str.count", str_len, args, vm)?; + let (sub, range) = parse_search_args("str.count", s, args, vm)?; + let Some((start, end)) = range else { + // `start` past `end` counts nothing: `'abc'.count('', 2, 1) == 0` + return Ok(Value::Int(0)); + }; let s = s.get(vm.heap); let slice = slice_string(s, start, end); let count = if sub.is_empty() { @@ -1036,7 +1082,6 @@ fn str_starts_ends_with<'h>( args: ArgValues, vm: &mut VM<'h>, ) -> RunResult { - let str_len = s.get(vm.heap).chars().count(); let pos = args.into_pos_only(method, vm.heap)?; defer_drop!(pos, vm); let [affix, rest @ ..] = pos.as_slice() else { @@ -1045,13 +1090,9 @@ fn str_starts_ends_with<'h>( if rest.len() > 2 { return Err(ExcType::type_error_at_most(method, 3, pos.len())); } - let start = match rest.first() { - Some(value) => optional_sequence_bound(value, 0, str_len, vm)?, - None => 0, - }; - let end = match rest.get(1) { - Some(value) => optional_sequence_bound(value, str_len, str_len, vm)?, - None => str_len, + let Some((start, end)) = string_search_range(s, rest, vm)? else { + // `start` past `end` matches nothing, but each affix is still type-checked + return Ok(Value::Bool(affix_matches(affix, "", method, |_, _| false, vm)?)); }; let slice = slice_string(s.get(vm.heap), start, end); Ok(Value::Bool(affix_matches(affix, slice, method, matcher, vm)?)) @@ -1073,88 +1114,79 @@ fn affix_matches( // CPython error messages use the bare method name, not "str.startswith". let short_method = method.strip_prefix("str.").unwrap_or(method); let check = |a: &str| matcher(slice, a); - match affix { - Value::InternString(id) => Ok(check(vm.interns.get_str(*id))), - Value::Ref(heap_id) => match vm.heap.get(*heap_id) { - HeapData::Str(a) => Ok(check(a.as_str())), - HeapData::Tuple(tuple) => { - for item in tuple.as_slice() { - let matched = match item { - Value::InternString(id) => check(vm.interns.get_str(*id)), - Value::Ref(hid) if let HeapData::Str(a) = vm.heap.get(*hid) => check(a.as_str()), - _ => { - return Err(ExcType::type_error_affix_tuple_item( - short_method, - "str", - &item.py_type_name(vm), - )); - } - }; - if matched { - return Ok(true); - } - } - Ok(false) + if let Some(text) = affix.as_str(vm) { + return Ok(check(text)); + } + + if let Value::Ref(heap_id) = affix + && let HeapData::Tuple(tuple) = vm.heap.get(*heap_id) + { + for item in tuple.as_slice() { + let Some(text) = item.as_str(vm) else { + return Err(ExcType::type_error_affix_tuple_item( + short_method, + "str", + &item.py_type_name(vm), + )); + }; + if check(text) { + return Ok(true); } - _ => Err(ExcType::type_error_affix_arg( - short_method, - "str", - &affix.py_type_name(vm), - )), - }, - _ => Err(ExcType::type_error_affix_arg( - short_method, - "str", - &affix.py_type_name(vm), - )), + } + return Ok(false); } + + Err(ExcType::type_error_affix_arg( + short_method, + "str", + &affix.py_type_name(vm), + )) } -/// Parses arguments for search methods (find, rfind, index, rindex, count, startswith, endswith). +/// Parses arguments for search methods (find, rfind, index, rindex, count). /// -/// Returns (substring, start, end) where start and end are character indices. -fn parse_search_args( +/// Returns the substring and the `(start, end)` character range to search, or +/// `None` for a `start` past `end`, where nothing is found (see [`search_range`]). +fn parse_search_args<'h>( method: &str, - str_len: usize, + s: &impl HeapView<'h, str>, args: ArgValues, - vm: &mut VM<'_>, -) -> RunResult<(String, usize, usize)> { + vm: &mut VM<'h>, +) -> RunResult<(String, SearchRange)> { let pos = args.into_pos_only(method, vm.heap)?; defer_drop!(pos, vm); match pos.as_slice() { - [sub_value] => { - let sub = extract_string_arg(sub_value, vm)?; - Ok((sub, 0, str_len)) - } - [sub_value, start_value] => { + [sub_value, bounds @ ..] if bounds.len() <= 2 => { let sub = extract_string_arg(sub_value, vm)?; - let start = optional_sequence_bound(start_value, 0, str_len, vm)?; - Ok((sub, start, str_len)) - } - [sub_value, start_value, end_value] => { - let sub = extract_string_arg(sub_value, vm)?; - let start = optional_sequence_bound(start_value, 0, str_len, vm)?; - let end = optional_sequence_bound(end_value, str_len, str_len, vm)?; - Ok((sub, start, end)) + let range = string_search_range(s, bounds, vm)?; + Ok((sub, range)) } [] => Err(ExcType::type_error_at_least(method, 1, 0)), _ => Err(ExcType::type_error_at_most(method, 3, pos.len())), } } +/// Normalizes explicit character bounds; entirely omitted/`None` bounds return `(0, usize::MAX)`. +/// `slice_string` treats that sentinel as the original UTF-8 without counting characters. +fn string_search_range<'h>(s: &impl HeapView<'h, str>, bounds: &[Value], vm: &mut VM<'h>) -> RunResult { + if bounds.iter().all(|bound| matches!(bound, Value::None)) { + return Ok(Some((0, usize::MAX))); + } + let text = s.get(vm.heap); + let length = if text.is_ascii() { + text.len() + } else { + text.chars().count() + }; + search_range(bounds.first(), bounds.get(1), length, vm) +} + /// Extracts a string from a Value, returning an error if not a string. fn extract_string_arg(value: &Value, vm: &mut VM<'_>) -> RunResult { - match value { - Value::InternString(id) => Ok(vm.interns.get_str(*id).to_owned()), - Value::Ref(heap_id) => { - if let HeapData::Str(s) = vm.heap.get(*heap_id) { - Ok(s.as_str().to_owned()) - } else { - Err(ExcType::type_error("expected str")) - } - } - _ => Err(ExcType::type_error("expected str")), - } + value + .as_str(vm) + .map(str::to_owned) + .ok_or_else(|| ExcType::type_error("expected str")) } /// Extracts an integer from a Value, returning an error if not an integer. @@ -1181,6 +1213,10 @@ fn extract_c_int_arg(value: &Value, vm: &mut VM<'_>) -> RunResult { /// Returns a substring of s from character index start to end; ASCII text is sliced by byte offset. fn slice_string(s: &str, start: usize, end: usize) -> &str { + // Omitted bounds refer to the original UTF-8, without a character-count scan. + if start == 0 && end == usize::MAX { + return s; + } if start >= end { return ""; } @@ -1302,6 +1338,9 @@ fn str_removesuffix<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM fn str_split<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { let SplitArgs { sep, maxsplit } = SplitArgs::from_args(args, vm)?; let (sep, maxsplit) = coerce_split_args(sep, maxsplit, vm)?; + // Guarded before the subject borrow, so a limit error mid-loop releases the pieces built so far. + let mut items_guard = DropGuard::new(Vec::new(), vm); + let (list_items, vm) = items_guard.as_parts_mut(); let s = s.get(vm.heap); let parts: Vec<&str> = match &sep { @@ -1311,32 +1350,37 @@ fn str_split<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) - return Err(ExcType::value_error_empty_separator()); } if maxsplit < 0 { - s.split(sep.as_str()).collect() + collect_checked(s.split(sep.as_str()), &vm.heap.tracker)? } else { // Safe cast: we've checked maxsplit >= 0 let max = usize::try_from(maxsplit).unwrap_or(usize::MAX); - s.splitn(max.saturating_add(1), sep.as_str()).collect() + collect_checked(s.splitn(max.saturating_add(1), sep.as_str()), &vm.heap.tracker)? } } None => { // Split on whitespace, filtering empty strings if maxsplit < 0 { - s.split(is_space).filter(|part| !part.is_empty()).collect() + collect_checked(s.split(is_space).filter(|part| !part.is_empty()), &vm.heap.tracker)? } else { // Safe cast: we've checked maxsplit >= 0 let max = usize::try_from(maxsplit).unwrap_or(usize::MAX); - split_whitespace_n(s, max) + split_whitespace_n(s, max, &vm.heap.tracker)? } } }; // Convert to list of strings (using interned empty string when applicable) - let mut list_items = Vec::with_capacity(parts.len()); + vm.heap + .tracker + .check_allocation(parts.len().saturating_mul(VALUE_SIZE))?; + // `with_capacity` allocates directly; `reserve` on the empty guarded `Vec` takes the grow path. + *list_items = Vec::with_capacity(parts.len()); for (i, part) in parts.into_iter().enumerate() { vm.heap.tracker.check_memory_time_every(i)?; list_items.push(allocate_string(part, vm.heap)); } + let (list_items, vm) = items_guard.into_parts(); let list = super::List::new(list_items); let heap_id = vm.heap.allocate(HeapData::List(list)); Ok(Value::Ref(heap_id)) @@ -1349,6 +1393,9 @@ fn str_split<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) - fn str_rsplit<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { let RsplitArgs { sep, maxsplit } = RsplitArgs::from_args(args, vm)?; let (sep, maxsplit) = coerce_split_args(sep, maxsplit, vm)?; + // Guarded before the subject borrow, so a limit error mid-loop releases the pieces built so far. + let mut items_guard = DropGuard::new(Vec::new(), vm); + let (list_items, vm) = items_guard.as_parts_mut(); let s = s.get(vm.heap); let parts: Vec<&str> = match &sep { @@ -1358,11 +1405,13 @@ fn str_rsplit<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) return Err(ExcType::value_error_empty_separator()); } if maxsplit < 0 { - s.rsplit(sep.as_str()).collect::>().into_iter().rev().collect() + let mut parts = collect_checked(s.rsplit(sep.as_str()), &vm.heap.tracker)?; + parts.reverse(); + parts } else { // Safe cast: we've checked maxsplit >= 0 let max = usize::try_from(maxsplit).unwrap_or(usize::MAX); - let mut parts: Vec<_> = s.rsplitn(max.saturating_add(1), sep.as_str()).collect(); + let mut parts = collect_checked(s.rsplitn(max.saturating_add(1), sep.as_str()), &vm.heap.tracker)?; parts.reverse(); parts } @@ -1370,22 +1419,27 @@ fn str_rsplit<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<'h>) None => { // Split on whitespace from right if maxsplit < 0 { - s.split(is_space).filter(|part| !part.is_empty()).collect() + collect_checked(s.split(is_space).filter(|part| !part.is_empty()), &vm.heap.tracker)? } else { // Safe cast: we've checked maxsplit >= 0 let max = usize::try_from(maxsplit).unwrap_or(usize::MAX); - rsplit_whitespace_n(s, max) + rsplit_whitespace_n(s, max, &vm.heap.tracker)? } } }; // Convert to list of strings (using interned empty string when applicable) - let mut list_items = Vec::with_capacity(parts.len()); + vm.heap + .tracker + .check_allocation(parts.len().saturating_mul(VALUE_SIZE))?; + // `with_capacity` allocates directly; `reserve` on the empty guarded `Vec` takes the grow path. + *list_items = Vec::with_capacity(parts.len()); for (i, part) in parts.into_iter().enumerate() { vm.heap.tracker.check_memory_time_every(i)?; list_items.push(allocate_string(part, vm.heap)); } + let (list_items, vm) = items_guard.into_parts(); let list = super::List::new(list_items); let heap_id = vm.heap.allocate(HeapData::List(list)); Ok(Value::Ref(heap_id)) @@ -1430,14 +1484,18 @@ struct RsplitArgs { } /// Split string on whitespace, returning at most `maxsplit + 1` parts. -fn split_whitespace_n(s: &str, maxsplit: usize) -> Vec<&str> { +fn split_whitespace_n<'a>( + s: &'a str, + maxsplit: usize, + tracker: &ResourceTracker, +) -> Result, ResourceError> { let mut parts = Vec::new(); let mut remaining = s.trim_start_matches(is_space); let mut count = 0; while !remaining.is_empty() && count < maxsplit { if let Some(end) = remaining.find(is_space) { - parts.push(&remaining[..end]); + push_checked(&mut parts, &remaining[..end], tracker)?; remaining = remaining[end..].trim_start_matches(is_space); count += 1; } else { @@ -1446,14 +1504,18 @@ fn split_whitespace_n(s: &str, maxsplit: usize) -> Vec<&str> { } if !remaining.is_empty() { - parts.push(remaining); + push_checked(&mut parts, remaining, tracker)?; } - parts + Ok(parts) } /// Split string on whitespace from the right, returning at most `maxsplit + 1` parts. -fn rsplit_whitespace_n(s: &str, maxsplit: usize) -> Vec<&str> { +fn rsplit_whitespace_n<'a>( + s: &'a str, + maxsplit: usize, + tracker: &ResourceTracker, +) -> Result, ResourceError> { let mut parts = Vec::new(); let mut remaining = s.trim_end_matches(is_space); let mut count = 0; @@ -1461,7 +1523,7 @@ fn rsplit_whitespace_n(s: &str, maxsplit: usize) -> Vec<&str> { while !remaining.is_empty() && count < maxsplit { if let Some(start) = remaining.rfind(is_space) { let ws_len = remaining[start..].chars().next().unwrap().len_utf8(); - parts.push(&remaining[start + ws_len..]); + push_checked(&mut parts, &remaining[start + ws_len..], tracker)?; remaining = remaining[..start].trim_end_matches(is_space); count += 1; } else { @@ -1470,11 +1532,11 @@ fn rsplit_whitespace_n(s: &str, maxsplit: usize) -> Vec<&str> { } if !remaining.is_empty() { - parts.push(remaining); + push_checked(&mut parts, remaining, tracker)?; } parts.reverse(); - parts + Ok(parts) } /// Implements Python's `str.splitlines(keepends?)` method. @@ -1495,9 +1557,11 @@ fn str_splitlines<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<' }; let keepends = parse_splitlines_args(args, vm)?; + // Guarded before the subject borrow, so a limit error mid-loop releases the lines built so far. + let mut lines_guard = DropGuard::new(Vec::new(), vm); + let (lines, vm) = lines_guard.as_parts_mut(); let s = s.get(vm.heap); - let mut lines = Vec::new(); let mut start = 0; let bytes = s.as_bytes(); let len = bytes.len(); @@ -1537,11 +1601,17 @@ fn str_splitlines<'h>(s: &impl HeapView<'h, str>, args: ArgValues, vm: &mut VM<' let line = if keepends { &s[start..end] } else { &s[start..line_end] }; + // Empty and short lines cost no heap entry, so the per-item poll alone + // cannot stop the buffer's own doubling crossing the hard limit. + vm.heap + .tracker + .check_growth(lines.len(), lines.capacity(), VALUE_SIZE)?; lines.push(allocate_string(line, vm.heap)); start = end; } + let (lines, vm) = lines_guard.into_parts(); let list = super::List::new(lines); let heap_id = vm.heap.allocate(HeapData::List(list)); Ok(Value::Ref(heap_id)) @@ -2001,6 +2071,7 @@ fn str_istitle(s: &str) -> bool { #[derive(Debug, serde::Serialize, serde::Deserialize)] enum StringIteratorSource { Intern(StringId), + Inline(InlineStr), Heap(HeapId), } @@ -2015,10 +2086,15 @@ pub(crate) struct StringIterator { impl StringIterator { /// Allocates an iterator over an interned string. pub(crate) fn from_intern(id: StringId, vm: &mut VM<'_>) -> Value { - let ascii = vm.interns.get_str(id).is_ascii(); + let ascii = vm.interns.str_is_ascii(id); Self::allocate(StringIteratorSource::Intern(id), ascii, vm) } + /// Allocates an iterator over a string stored inside its `Value`. + pub(crate) fn from_inline(text: InlineStr, vm: &mut VM<'_>) -> Value { + Self::allocate(StringIteratorSource::Inline(text), text.as_bytes().is_ascii(), vm) + } + /// Allocates an iterator retaining a heap string. fn from_heap(id: HeapId, ascii: bool, vm: &mut VM<'_>) -> Value { Self::allocate(StringIteratorSource::Heap(id), ascii, vm) @@ -2033,10 +2109,11 @@ impl StringIterator { } } - /// Returns a retained heap source, if the string is not interned. + /// Returns the heap source when the iterator retains one. pub(crate) fn source_id(&self) -> Option { match self.source { StringIteratorSource::Intern(_) => None, + StringIteratorSource::Inline(_) => None, StringIteratorSource::Heap(id) => Some(id), } } @@ -2047,10 +2124,11 @@ impl StringIterator { } /// Borrows the unconsumed string suffix. - fn as_str<'a>(&self, vm: &'a VM<'_>) -> &'a str { - let string = match self.source { - StringIteratorSource::Intern(id) => vm.interns.get_str(id), - StringIteratorSource::Heap(id) => match vm.heap.get(id) { + fn as_str<'a>(&'a self, vm: &'a VM<'_>) -> &'a str { + let string = match &self.source { + StringIteratorSource::Intern(id) => vm.interns.get_str(*id), + StringIteratorSource::Inline(text) => text.as_str(), + StringIteratorSource::Heap(id) => match vm.heap.get(*id) { HeapData::Str(string) => string.as_str(), _ => unreachable!("string iterator must retain a string"), }, @@ -2063,6 +2141,7 @@ impl StringIterator { let source_id = match source { StringIteratorSource::Heap(id) => Some(id), StringIteratorSource::Intern(_) => None, + StringIteratorSource::Inline(_) => None, }; let id = vm.heap.allocate(HeapData::StringIterator(Self { source, @@ -2108,7 +2187,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, StringIterator> { fn py_next(&mut self, vm: &mut VM<'h>) -> RunResult> { let next = self.get(vm.heap).as_str(vm).chars().next(); if let Some(character) = next { - let value = allocate_char(character, vm.heap); + let value = allocate_char(character); self.get_mut(vm.heap).byte_offset += character.len_utf8(); Ok(Some(value)) } else { @@ -2122,24 +2201,133 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, StringIterator> { /// Shared by logical string views and concrete heap dispatch. /// A non-str probe reports its own type, as CPython does. pub(crate) fn str_contains(container_str: &str, item: &Value, heap: &Heap, interns: &Interns) -> RunResult { - match item { - Value::InternString(item_id) => { - let item_str = interns.get_str(*item_id); - Ok(container_str.contains(item_str)) - } - Value::Ref(item_heap_id) => { - if let HeapData::Str(item_str) = heap.get(*item_heap_id) { - Ok(container_str.contains(item_str.as_str())) - } else { - Err(ExcType::type_error(format!( - "'in ' requires string as left operand, not {}", - item.py_type_name_heap(heap, interns) - ))) - } - } - _ => Err(ExcType::type_error(format!( + if let Some(text) = item.as_str_heap(heap, interns) { + Ok(container_str.contains(text)) + } else { + Err(ExcType::type_error(format!( "'in ' requires string as left operand, not {}", item.py_type_name_heap(heap, interns) - ))), + ))) } } + +#[cfg(test)] +mod tests { + use monty_types::PrintWriter; + + use super::*; + use crate::run::{Program, SessionTables}; + + #[test] + fn characters_use_reserved_or_inline_storage() { + for character in ['\0', 'a', '\x7f'] { + assert!( + matches!(allocate_char(character), Value::InternString(id) if id == StringId::from_ascii(character as u8)) + ); + } + for character in ['é', '中', '🐍'] { + let Value::InlineString(text) = allocate_char(character) else { + unreachable!("non-ASCII characters fit inline") + }; + assert_eq!(text.as_str(), character.to_string()); + } + } + + #[test] + fn comparisons_agree_across_string_storage_kinds() { + let texts = [ + "", + "\0", + "\0\0", + "a", + "a\0", + "a\0\0", + "1234", + "1235", + "é", + "é\0", + "🐍", + "éééééééa", + "abcdefghijklmno", + "abcdefghijklmn", + "\u{e000}", + "\u{10000}", + ]; + let mut heap = Heap::new(16, ResourceTracker::default()); + let mut tables = SessionTables::default(); + let program = Program::for_tests(); + let ids: Vec<_> = { + let mut interns = crate::intern::CompileInterns::direct(&mut tables.interns); + texts.iter().map(|text| interns.intern(text)).collect() + }; + + HeapReader::with(&mut heap, &mut (&program, &mut tables), |reader, (program, tables)| { + let vm = &mut VM::new(Vec::new(), tables, program, reader, PrintWriter::Disabled); + let values: Vec<_> = texts + .iter() + .zip(ids) + .flat_map(|(text, id)| { + [ + Value::InternString(id), + Value::InlineString(InlineStr::new(text).unwrap()), + allocate_string_on_heap(*text, vm.heap), + ] + }) + .collect(); + defer_drop!(values, vm); + + for lhs in values { + for rhs in values { + let expected = lhs.as_str(vm) == rhs.as_str(vm); + assert_eq!(lhs.py_eq_impl(rhs, vm).unwrap(), Some(expected)); + assert_eq!(lhs.py_eq_operator(rhs, vm).unwrap(), expected); + let view = PyStr::from_value(lhs, vm).unwrap(); + assert_eq!(view.py_eq_impl(rhs, vm).unwrap(), Some(expected)); + let order = lhs.as_str(vm).unwrap().cmp(rhs.as_str(vm).unwrap()); + assert_eq!(lhs.py_cmp(rhs, vm).unwrap(), CmpOrder::Ordered(order)); + } + assert_eq!(lhs.py_eq_impl(&Value::Int(7), vm).unwrap(), None); + let view = PyStr::from_value(lhs, vm).unwrap(); + assert_eq!(view.py_eq_impl(&Value::Int(7), vm).unwrap(), None); + } + }); + } + + #[test] + fn string_views_preserve_identity_and_content_across_storage_kinds() { + let mut heap = Heap::new(16, ResourceTracker::default()); + let mut tables = SessionTables::default(); + let program = Program::for_tests(); + + HeapReader::with(&mut heap, &mut (&program, &mut tables), |reader, (program, tables)| { + let vm = &mut VM::new(Vec::new(), tables, program, reader, PrintWriter::Disabled); + let values = vec![ + Value::InternString(StringId::from_ascii(b'a')), + allocate_string("abcdefghijklmno", vm.heap), + allocate_string_on_heap("abcdefghijklmno", vm.heap), + ]; + defer_drop!(values, vm); + + for value in values { + let view = PyStr::from_value(value, vm).unwrap(); + assert_eq!(view.py_type(vm), Type::Str); + assert!(view.py_identity() == Identity::new(value)); + assert_eq!(view.py_eq_impl(&Value::Int(7), vm).unwrap(), None); + + let text = view.as_str(vm).to_owned(); + let equal = allocate_string_on_heap(text.clone(), vm.heap); + defer_drop!(equal, vm); + assert_eq!(view.py_eq_impl(equal, vm).unwrap(), Some(true)); + + let copied = view.py_str(vm).unwrap(); + defer_drop!(copied, vm); + assert_eq!(copied.as_str(vm), Some(text.as_str())); + assert!(Identity::new(copied) == Identity::new(value)); + } + }); + } +} + +#[cfg(test)] +#[path = "../../tests/unit/format_template.rs"] +mod format_template_tests; diff --git a/crates/bashkit-monty/src/types/timedelta.rs b/crates/bashkit-monty/src/types/timedelta.rs index 4aa734936..d6440f44c 100644 --- a/crates/bashkit-monty/src/types/timedelta.rs +++ b/crates/bashkit-monty/src/types/timedelta.rs @@ -434,18 +434,17 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, TimeDelta> { fn py_add_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { match other.read_heap(vm) { - Some(HeapReadOutput::Date(other)) => Ok(date::py_add(*other.get(vm.heap), *self.get(vm.heap), vm.heap)), + Some(HeapReadOutput::Date(other)) => { + date::py_add(*other.get(vm.heap), *self.get(vm.heap), vm.heap).map(Some) + } Some(HeapReadOutput::DateTime(other)) => { let other = other.get(vm.heap).clone(); let value = *self.get(vm.heap); - Ok(datetime::py_add(&other, &value, vm.heap)) + datetime::py_add(&other, &value, vm.heap).map(Some) } Some(HeapReadOutput::TimeDelta(other)) => { - let total = total_microseconds(self.get(vm.heap)).checked_add(total_microseconds(other.get(vm.heap))); - let Some(total) = total else { return Ok(None) }; - let Ok(result) = from_total_microseconds(total) else { - return Ok(None); - }; + let total = total_microseconds(self.get(vm.heap)) + total_microseconds(other.get(vm.heap)); + let result = from_total_microseconds(total)?; Ok(Some(Value::Ref(vm.heap.allocate(HeapData::TimeDelta(result))))) } _ => Ok(None), @@ -456,11 +455,8 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, TimeDelta> { let Some(HeapReadOutput::TimeDelta(other)) = other.read_heap(vm) else { return Ok(None); }; - let total = total_microseconds(self.get(vm.heap)).checked_sub(total_microseconds(other.get(vm.heap))); - let Some(total) = total else { return Ok(None) }; - let Ok(result) = from_total_microseconds(total) else { - return Ok(None); - }; + let total = total_microseconds(self.get(vm.heap)) - total_microseconds(other.get(vm.heap)); + let result = from_total_microseconds(total)?; Ok(Some(Value::Ref(vm.heap.allocate(HeapData::TimeDelta(result))))) } diff --git a/crates/bashkit-monty/src/types/timezone.rs b/crates/bashkit-monty/src/types/timezone.rs index ec9e72d4d..23d09c230 100644 --- a/crates/bashkit-monty/src/types/timezone.rs +++ b/crates/bashkit-monty/src/types/timezone.rs @@ -264,14 +264,10 @@ pub(crate) fn format_offset_timedelta_repr(offset_seconds: i32) -> String { } fn extract_name(name_arg: &Value, heap: &Heap, interns: &Interns) -> RunResult> { - match name_arg { - Value::InternString(id) => Ok(Some(interns.get_str(*id).to_owned())), - Value::Ref(id) => match heap.get(*id) { - HeapData::Str(s) => Ok(Some(s.as_str().to_owned())), - _ => Err(bad_name_arg(name_arg, heap, interns)), - }, - _ => Err(bad_name_arg(name_arg, heap, interns)), - } + name_arg + .try_to_str_heap(heap, interns) + .map(|name| Some(name.to_owned())) + .map_err(|_| bad_name_arg(name_arg, heap, interns)) } /// Builds the `timezone() argument 2 must be str, not ` error CPython diff --git a/crates/bashkit-monty/src/types/tuple.rs b/crates/bashkit-monty/src/types/tuple.rs index c9ef3e524..9d2457a68 100644 --- a/crates/bashkit-monty/src/types/tuple.rs +++ b/crates/bashkit-monty/src/types/tuple.rs @@ -35,11 +35,10 @@ use crate::{ heap::{DropGuard, DropWithContext, Heap, HeapData, HeapId, HeapItem, HeapObjectRead, HeapRead, HeapReadOutput}, intern::StaticStrings, modules::copy::{Memo, PyDeepCopy, deep_copy_slots}, - resource_checks::check_repeat_size, + resource_checks::{check_repeat_size, repeated_len}, types::{ LazyHeapSet, Type, list::repr_sequence_fmt, - long_int::repeat_count, slice::{normalize_sequence_index, slice_collect_iterator, value_to_i64_bound}, }, value::{EitherStr, VALUE_SIZE, Value}, @@ -437,30 +436,40 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Tuple> { let Some(HeapReadOutput::Tuple(other)) = other.read_heap(vm) else { return Ok(None); }; - let mut items = self.clone_all_items(vm)?; - items.extend(other.clone_all_items(vm)?); + // The guard releases our clones if cloning `other` hits the memory limit. + let mut items = DropGuard::new(self.clone_all_items(vm)?, vm); + let (left, vm) = items.as_parts_mut(); + left.extend(other.clone_all_items(vm)?); + let (items, vm) = items.into_parts(); Ok(Some(allocate_tuple(items, vm.heap))) } fn py_mul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { - let Some(count) = repeat_count(other, vm)? else { + let Some(count) = other.py_value(vm).repeat_count(vm)? else { return Ok(None); }; - let value = self.get(vm.heap); - if count == 0 || value.as_slice().is_empty() { + let len = self.get(vm.heap).as_slice().len(); + if count == 0 || len == 0 { return Ok(Some(vm.heap.get_empty_tuple())); } - check_repeat_size( - value.as_slice().len().saturating_mul(mem::size_of::()), - count, - &vm.heap.tracker, - )?; - let mut result = SmallVec::with_capacity(value.as_slice().len() * count); + let total = repeated_len(len, count, VALUE_SIZE)?; + check_repeat_size(len.saturating_mul(VALUE_SIZE), count, &vm.heap.tracker)?; + let mut items = TupleVec::new(); + items + .try_reserve_exact(total) + .map_err(|_| ExcType::allocation_too_large())?; + // The guard releases the clones built so far if the time poll trips. + let mut result = DropGuard::new(items, vm); for rep in 0..count { - result.extend(value.as_slice().iter().map(|value| value.clone_with_heap(vm.heap))); + let (items, vm) = result.as_parts_mut(); + // Pushes, not `extend`: its per-call reserve dominates when each pass adds one item. + for value in self.get(vm.heap).as_slice() { + items.push(value.clone_with_heap(vm.heap)); + } vm.heap.tracker.check_time_every(rep)?; } - Ok(Some(allocate_tuple(result, vm.heap))) + let (items, vm) = result.into_parts(); + Ok(Some(allocate_tuple(items, vm.heap))) } fn py_rmul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { diff --git a/crates/bashkit-monty/src/types/type.rs b/crates/bashkit-monty/src/types/type.rs index d1eb16217..56553fa3b 100644 --- a/crates/bashkit-monty/src/types/type.rs +++ b/crates/bashkit-monty/src/types/type.rs @@ -8,8 +8,8 @@ use crate::{ bytecode::{CallResult, VM}, defer_drop, exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, - heap::{DropWithContext, Heap, HeapData, HeapId}, - intern::{Interns, StaticStrings, StringId}, + heap::{DropWithContext, Heap, HeapId}, + intern::{Interns, StaticStrings}, modules::{ ModuleFunctions, collections, csv, hashlib::{self, Blake2Kind}, @@ -18,8 +18,8 @@ use crate::{ }, py_value::PyValue, types::{ - Bytes, Deque, Dict, FrozenSet, GenericAlias, List, LongInt, Partial, Path, PyTrait, Random, Range, Set, Slice, - Str, TimeZone, Tuple, + Bytes, Deque, Dict, ForwardRef, FrozenSet, GenericAlias, List, LongInt, Partial, Path, PyTrait, Random, Range, + Set, Slice, Str, TimeZone, Tuple, bytes::{bytes_fromhex, bytes_repr}, complex, date, datetime, decimal, dict::{DictKind, dict_fromkeys}, @@ -40,6 +40,9 @@ use crate::{ /// Some variants are Python builtins accessible by name (e.g., `int`, `list`), /// while others are internal types only available through imports or introspection /// (e.g., `TextIOWrapper`, `PosixPath`). +/// +/// Variant names are persisted in dumps; renames require a serde alias. +/// Variant order is also used by builtin id() through postcard. #[derive( Debug, Clone, @@ -104,7 +107,7 @@ pub enum Type { DictValues, Set, FrozenSet, - /// The type of a host-backed class instance ([`HeapData::HostClass`]), + /// The type of a host-backed class instance ([`crate::heap::HeapData::HostClass`]), /// for internal dispatch only: `type(x)` materializes a `HostClassType` /// instead, so it never reaches Python code or the host boundary. /// @@ -120,11 +123,12 @@ pub enum Type { /// reference — `Type` is `Copy`, untracked by refcounting, and has no /// `Drop`. A `Type::Instance` is only valid while the value it was derived /// from is alive (an instance holds a counted ref to its class, taken in - /// `VM::instantiate_class`). It must NEVER be stored long-lived, + /// `VM::instantiate_class` or `allocate_empty_like`). It must NEVER be stored long-lived, /// serialized into snapshots/const pools, placed in `Builtins::Type` (the /// `type()` builtin returns the class object itself for instances), or /// converted to `MontyType`, which has no class variant (a sandbox class /// crosses the boundary as its own `ClassType` arena node). + /// `Builtins::Type` now accepts only `BuiltinType`, preventing storage there at compile time. #[strum(disabled)] Instance(HeapId), /// Exception types render/parse via `ExcType`'s own strum name @@ -338,11 +342,14 @@ pub enum Type { /// The manager `decimal.localcontext()` returns. #[strum(serialize = "decimal.ContextManager")] DecimalContextManager, + /// `annotationlib.ForwardRef`, an unevaluated annotation. + #[strum(serialize = "annotationlib.ForwardRef")] + ForwardRef, } /// Writes the canonical static name of every non-[`Instance`](Type::Instance) -/// variant — the single name table backing [`Type::name`] and `MontyType`'s -/// `Display`. +/// variant, using the same name table as [`Type::name`]. +/// `MontyType` has its own strum-derived name table in `monty-types`. /// /// The names live on the enum via the `IntoStaticStr` derive /// (`serialize_all = "lowercase"` plus per-variant `serialize` overrides); @@ -352,10 +359,9 @@ pub enum Type { /// On `Instance`, which has no static name — callers with heap access must /// resolve the real class name via [`Type::name`]. Well-formed data never /// puts an `Instance` where no heap exists (`Builtins::Type`, `MontyObject`, -/// the wire protocol), so this is a programmer-error tripwire. A crafted -/// snapshot payload *can* smuggle one in, but snapshot bytes are not a -/// panic-free boundary anyway — any bogus `HeapId` in them panics on first -/// heap access. +/// the wire protocol), so this is a programmer-error tripwire. +/// `BuiltinType` rejects `Instance` during snapshot deserialization, including +/// for `Builtins::Type` and generic alias origins. impl fmt::Display for Type { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match *self { @@ -635,13 +641,8 @@ impl Type { /// Keeps classmethod behavior centralized with type semantics instead of VM /// call plumbing. Any other name is looked up as a plain attribute and the /// result called, so `list.__name__()` raises `'str' object is not callable`. - pub(crate) fn call_class_method( - self, - method_id: StringId, - args: ArgValues, - vm: &mut VM<'_>, - ) -> RunResult { - match (self, vm.interns.static_string(method_id)) { + pub(crate) fn call_class_method(self, attr: &EitherStr, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + match (self, attr.static_string(vm.interns)) { // Type-level `dict.fromkeys(...)`, so the result is a plain dict. (Self::Dict, Some(StaticStrings::Fromkeys)) => { dict_fromkeys(args, DictKind::plain(), vm).map(CallResult::Value) @@ -667,7 +668,7 @@ impl Type { (Self::Decimal, Some(StaticStrings::FromNumber)) => { decimal::py::class_from_number(vm, args).map(CallResult::Value) } - (Self::Decimal, _) if vm.interns.get_str(method_id) == "from_float" => { + (Self::Decimal, _) if attr.as_str(vm.interns) == "from_float" => { decimal::py::class_from_float(vm, args).map(CallResult::Value) } (Self::Date, Some(StaticStrings::Today)) => date::class_today(vm, args), @@ -675,6 +676,12 @@ impl Type { (Self::Date, Some(StaticStrings::Fromisoformat)) => { date::class_fromisoformat(vm.heap, args, vm.interns).map(CallResult::Value) } + (Self::Date, Some(StaticStrings::Fromtimestamp)) => { + date::class_fromtimestamp(vm, args).map(CallResult::Value) + } + (Self::DateTime, Some(StaticStrings::Fromtimestamp)) => { + datetime::class_fromtimestamp(vm, args).map(CallResult::Value) + } (Self::DateTime, Some(StaticStrings::Now)) => datetime::class_now(vm, args), (Self::DateTime, Some(StaticStrings::Strptime)) => { datetime::class_strptime(vm.heap, args, vm.interns).map(CallResult::Value) @@ -685,7 +692,7 @@ impl Type { // `object.__setattr__(obj, name, value)` called directly, which is // how it is nearly always reached; `object.__setattr__` as a value // is handled by `class_getattr`. - (Self::Object, _) if vm.interns.get_str(method_id) == "__setattr__" => { + (Self::Object, _) if attr.as_str(vm.interns) == "__setattr__" => { builtin_object_setattr(vm, args).map(CallResult::Value) } (Self::DateTime, Some(StaticStrings::Combine)) => datetime::class_combine(vm, args).map(CallResult::Value), @@ -697,18 +704,21 @@ impl Type { (ty, Some(StaticStrings::ClassGetitem)) if ty.has_class_getitem() => { let name = format!("{}.__class_getitem__", ty.dunder_name(vm.heap, vm.interns)); let key = args.get_one_arg(&name, vm.heap)?; - Ok(CallResult::Value(GenericAlias::subscript(ty, key, vm))) + Ok(CallResult::Value(GenericAlias::subscript( + ty.try_into().expect("generic origins are builtin types"), + key, + vm, + ))) } // The type's plain attributes (`list.__name__`); a missing name // raises the lookup's `type object 'list' has no attribute` error. _ => { - let attr = EitherStr::Interned(method_id); - if let Some(value) = self.class_getattr(&attr, vm) { + if let Some(value) = self.class_getattr(attr, vm) { defer_drop!(value, vm); vm.call_function(value, args) } else { args.drop_with(vm.heap); - Err(self.attribute_error(&attr, vm)) + Err(self.attribute_error(attr, vm)) } } } @@ -825,6 +835,7 @@ impl Type { Self::TimeDelta => timedelta::init(vm, args), Self::TimeZone => TimeZone::init(vm, args), Self::Path => Path::init(vm, args), + Self::ForwardRef => ForwardRef::init(vm, args), Self::Partial => Partial::init(vm, args), Self::Random => Random::init(vm, args), Self::Blake2b => hashlib::blake2_init(Blake2Kind::Blake2b, vm, args), @@ -865,7 +876,6 @@ impl Type { // Primitive types - inline implementation Self::Int => int_init(vm, args), Self::Float => { - let interns = vm.interns; let Some(v) = args.get_zero_one_arg("float", vm.heap)? else { return Ok(Value::Float(0.0)); }; @@ -873,13 +883,9 @@ impl Type { if let Some(value) = v.py_float(vm)? { Ok(Value::Float(value)) } else { - match v { - Value::InternString(string_id) => { - Ok(Value::Float(parse_f64_from_str(interns.get_str(*string_id))?)) - } - Value::Ref(heap_id) if let HeapData::Str(s) = vm.heap.get(*heap_id) => { - Ok(Value::Float(parse_f64_from_str(s.as_str())?)) - } + match v.py_value(vm) { + PyValue::Str(value) => Ok(Value::Float(parse_f64_from_str(value.as_str(vm))?)), + PyValue::Bytes(value) => Ok(Value::Float(parse_f64_from_bytes(value.as_slice(vm))?)), _ => Err(ExcType::type_error_float_conversion(&v.py_type_name(vm))), } } @@ -914,13 +920,27 @@ impl Type { /// - The special values `inf`, `-inf`, `infinity`, and `nan` (case-insensitive) /// - Underscore digit separators, strictly between two digits (`1_000.5`, `1e1_0`) pub(crate) fn parse_f64_from_str(value: &str) -> RunResult { + parse_f64(value).ok_or_else(|| value_error_could_not_convert_string_to_float(StringRepr(value))) +} + +/// Parses ASCII bytes without accepting Unicode digits or whitespace encoded as UTF-8. +fn parse_f64_from_bytes(value: &[u8]) -> RunResult { + str::from_utf8(value) + .ok() + .filter(|text| text.is_ascii()) + .and_then(parse_f64) + .ok_or_else(|| value_error_could_not_convert_string_to_float(bytes_repr(value))) +} + +/// Parses shared float syntax without constructing the caller-specific error. +fn parse_f64(value: &str) -> Option { let trimmed = value.trim(); if trimmed.is_empty() { - return Err(value_error_could_not_convert_string_to_float(value)); + return None; } let stripped; let trimmed = if trimmed.contains('_') { - stripped = strip_underscores(trimmed).ok_or_else(|| value_error_could_not_convert_string_to_float(value))?; + stripped = strip_underscores(trimmed)?; stripped.as_str() } else { trimmed @@ -932,12 +952,10 @@ pub(crate) fn parse_f64_from_str(value: &str) -> RunResult { "-inf" | "-infinity" => f64::NEG_INFINITY, "nan" | "+nan" => f64::NAN, "-nan" => -f64::NAN, - _ => trimmed - .parse::() - .map_err(|_| value_error_could_not_convert_string_to_float(value))?, + _ => trimmed.parse::().ok()?, }; - Ok(parsed) + Some(parsed) } /// Removes digit-separator underscores, or returns `None` when one is not @@ -959,13 +977,11 @@ pub(crate) fn strip_underscores(text: &str) -> Option { Some(out) } -/// Creates the `ValueError` raised by `float()` when a string cannot be parsed. -/// -/// Matches CPython's message format: `could not convert string to float: '...'`. -fn value_error_could_not_convert_string_to_float(value: &str) -> RunError { +/// Creates a `float()` ValueError using the original str/bytes argument's Python representation. +fn value_error_could_not_convert_string_to_float(value: impl fmt::Display) -> RunError { SimpleException::new_msg( ExcType::ValueError, - format!("could not convert string to float: {}", StringRepr(value)), + format!("could not convert string to float: {value}"), ) .into() } @@ -1002,15 +1018,9 @@ fn int_init(vm: &mut VM<'_>, args: ArgValues) -> RunResult { None => int_convert(x, vm), Some(base) => { let base = int_base(base, vm)?; - let interns = vm.interns; - match x { - Value::InternString(string_id) => parse_int_from_str(interns.get_str(*string_id), base, vm.heap), - Value::InternBytes(bytes_id) => parse_int_from_bytes(interns.get_bytes(*bytes_id), base, vm.heap), - Value::Ref(heap_id) => match vm.heap.get(*heap_id) { - HeapData::Str(s) => parse_int_from_str(s.as_str(), base, vm.heap), - HeapData::Bytes(b) => parse_int_from_bytes(b.as_slice(), base, vm.heap), - _ => Err(ExcType::type_error_int_non_string_with_base()), - }, + match x.py_value(vm) { + PyValue::Str(value) => parse_int_from_str(value.as_str(vm), base, vm.heap), + PyValue::Bytes(value) => parse_int_from_bytes(value.as_slice(vm), base, vm.heap), _ => Err(ExcType::type_error_int_non_string_with_base()), } } diff --git a/crates/bashkit-monty/src/types/union.rs b/crates/bashkit-monty/src/types/union.rs index e7a2ac1e0..750389054 100644 --- a/crates/bashkit-monty/src/types/union.rs +++ b/crates/bashkit-monty/src/types/union.rs @@ -23,7 +23,10 @@ use crate::{ HeapReadOutput, }, intern::StaticStrings, - types::{LazyHeapSet, PyTrait, Type, generic_alias::repr_type_arg, list::repr_check_time, tuple::allocate_tuple}, + types::{ + BuiltinType, LazyHeapSet, PyTrait, Type, generic_alias::repr_type_arg, list::repr_should_truncate, + tuple::allocate_tuple, + }, value::{EitherStr, VALUE_SIZE, Value}, }; @@ -106,7 +109,9 @@ impl Union { defer_drop!(key, vm); let repr = key.py_repr(vm)?; defer_drop!(repr, vm); - Err(ExcType::optional_requires_single_type(repr.to_str(vm)?)) + Err(ExcType::optional_requires_single_type( + repr.as_str(vm).expect("py_repr returns str"), + )) } else { Self::from_members(vec![key, Value::None], vm) } @@ -119,7 +124,7 @@ impl Union { /// Deduplication is a linear scan per member, so a union built from a /// huge tuple is quadratic; the loop polls the time limit rather than /// running to completion. - fn from_members(members: Vec, vm: &mut VM<'_>) -> RunResult { + pub(crate) fn from_members(members: Vec, vm: &mut VM<'_>) -> RunResult { defer_drop!(members, vm); let mut guard = DropGuard::new(Vec::new(), vm); let (flat, vm) = guard.as_parts_mut(); @@ -188,7 +193,7 @@ impl Union { /// `None` is stored as `NoneType`, which is what `__args__` reports. fn push_unique(flat: &mut Vec, member: &Value, vm: &mut VM<'_>) -> RunResult<()> { let member = match member { - Value::None => Value::Builtin(Builtins::Type(Type::NoneType)), + Value::None => Value::Builtin(Builtins::Type(BuiltinType::NoneType)), other => other.clone_with_heap(vm), }; defer_drop!(member, vm); @@ -359,8 +364,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Union> { let count = args.get(vm.heap).as_slice().len(); for index in 0..count { if index > 0 { - // bashkit fork: `?` so a time hit errors instead of truncating (see `repr_check_time`). - if repr_check_time(index, vm)? { + if repr_should_truncate(index, vm)? { f.write_str(" | ...[timeout]")?; break; } @@ -368,7 +372,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Union> { } let member = args.clone_item(index, vm); defer_drop!(member, vm); - if matches!(member, Value::Builtin(Builtins::Type(Type::NoneType))) { + if matches!(member, Value::Builtin(Builtins::Type(BuiltinType::NoneType))) { f.write_str("None")?; } else { repr_type_arg(member, f, vm, heap_ids)?; @@ -383,9 +387,9 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Union> { fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> RunResult> { match attr.static_string(vm.interns) { Some(StaticStrings::DunderArgs) => Ok(Some(CallResult::Value(self.get(vm.heap).args(vm.heap)))), - Some(StaticStrings::DunderOrigin) => { - Ok(Some(CallResult::Value(Value::Builtin(Builtins::Type(Type::Union))))) - } + Some(StaticStrings::DunderOrigin) => Ok(Some(CallResult::Value(Value::Builtin(Builtins::Type( + BuiltinType::Union, + ))))), Some(StaticStrings::DunderParameters) => Ok(Some(CallResult::Value(vm.heap.get_empty_tuple()))), _ => Ok(None), } diff --git a/crates/bashkit-monty/src/value.rs b/crates/bashkit-monty/src/value.rs index ef87bb924..7d5c961f5 100644 --- a/crates/bashkit-monty/src/value.rs +++ b/crates/bashkit-monty/src/value.rs @@ -3,7 +3,7 @@ use std::{ cmp::Ordering, fmt::{self, Write}, mem, - str::FromStr, + str::{self, FromStr}, }; use num_bigint::{BigInt, Sign}; @@ -12,12 +12,13 @@ use serde::de::Error as _; use smallvec::smallvec; use crate::{ + annotations, builtins::Builtins, bytecode::{CallResult, VM}, defer_drop, exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, expressions::CmpOperator, - hash::{HashValue, hash_f64, hash_named, hash_one, identity_hash}, + hash::{HashValue, hash_f64, hash_named, hash_one, hash_python_str}, heap::{ContainsHeap, DropWithContext, Heap, HeapData, HeapId, HeapReadOutput}, identity::Identity, intern::{BytesId, FunctionId, Interns, LongIntId, StaticStrings, StringId}, @@ -27,6 +28,7 @@ use crate::{ BytesIterator, CmpOrder, Complex, LazyHeapSet, Property, PyTrait, StringIterator, Type, bytes::PyBytes, decimal, host_class_type, + inline_str::InlineStr, instance::{class_defines, instance_getattr, instance_str, instance_user_eq}, long_int::{ PyInt, bigint_cmp_f64, bigint_cmp_i64, bigint_divmod_tuple, bigint_eq_f64, bigint_eq_i64, i64_cmp_f64, @@ -39,9 +41,7 @@ use crate::{ /// Primary value type representing Python objects at runtime. /// -/// This enum uses a hybrid design: small immediate values (Int, Bool, None) are stored -/// inline, while heap-allocated values (List, Str, Dict, etc.) are stored in the arena -/// and referenced via `Ref(HeapId)`. +/// Stores immediate values directly and arena objects through `Ref(HeapId)`. /// /// NOTE: `Clone` is intentionally NOT derived. Use `clone_with_heap()`. Direct cloning via `.clone()` would /// bypass reference counting and cause memory leaks. @@ -68,6 +68,9 @@ pub(crate) enum Value { /// To get the actual string content, use `interns.get(string_id)`. #[serde(rename = "T")] InternString(StringId), + /// A short UTF-8 string stored directly in the value slot. + #[serde(rename = "S")] + InlineString(InlineStr), /// An interned bytes literal. The BytesId references the bytes in the Interns table. /// To get the actual bytes content, use `interns.get_bytes(bytes_id)`. #[serde(rename = "R")] @@ -255,6 +258,7 @@ impl<'h> PyTrait<'h> for Value { Self::Int(_) | Self::InternLongInt(_) => Type::Int, Self::Float(_) => Type::Float, Self::InternString(_) => Type::Str, + Self::InlineString(_) => Type::Str, Self::InternBytes(_) => Type::Bytes, Self::Builtin(c) => c.py_type(), Self::ModuleFunction(_) => Type::BuiltinFunction, @@ -288,6 +292,7 @@ impl<'h> PyTrait<'h> for Value { Self::InternString(o) => Some(id == o), _ => eq_str(vm.interns.get_str(*id), other, vm), }), + Self::InlineString(text) => Ok(text.eq_value(other, vm)), Self::InternBytes(id) => Ok(match other { // Fast path for the same interned bytes; otherwise compare content // (interned bytes are not deduplicated, unlike strings). @@ -391,6 +396,22 @@ impl<'h> PyTrait<'h> for Value { (Self::InternString(s1), Self::InternString(s2)) => { Ok(CmpOrder::Ordered(interns.get_str(*s1).cmp(interns.get_str(*s2)))) } + (Self::InlineString(text), Self::Ref(id)) if let HeapData::Str(value) = vm.heap.get(*id) => { + Ok(CmpOrder::Ordered(text.as_bytes().cmp(value.as_str().as_bytes()))) + } + (Self::Ref(id), Self::InlineString(text)) if let HeapData::Str(value) = vm.heap.get(*id) => { + Ok(CmpOrder::Ordered(value.as_str().as_bytes().cmp(text.as_bytes()))) + } + (Self::InlineString(left), Self::InlineString(right)) => { + // UTF-8 byte order matches Unicode scalar order, including prefixes. + Ok(CmpOrder::Ordered(left.as_bytes().cmp(right.as_bytes()))) + } + (Self::InlineString(text), Self::InternString(id)) => { + Ok(CmpOrder::Ordered(text.as_bytes().cmp(interns.get_str(*id).as_bytes()))) + } + (Self::InternString(id), Self::InlineString(text)) => { + Ok(CmpOrder::Ordered(interns.get_str(*id).as_bytes().cmp(text.as_bytes()))) + } // Cross-type string comparisons: interned vs heap-allocated (Self::InternString(s1), Self::Ref(id2)) if let HeapData::Str(s2) = vm.heap.get(*id2) => { Ok(CmpOrder::Ordered(interns.get_str(*s1).cmp(s2.as_str()))) @@ -461,6 +482,7 @@ impl<'h> PyTrait<'h> for Value { // same value back (inc-ref'd for the heap case) instead of cloning // the bytes into a fresh allocation. Self::InternString(string_id) => Ok(Self::InternString(*string_id)), + Self::InlineString(text) => Ok(Self::InlineString(*text)), Self::Ref(id) if matches!(vm.heap.get(*id), HeapData::Str(_)) => Ok(self.clone_with_heap(vm.heap)), // Instances dispatch to a user `__str__`/`__repr__` (needs the heap id). Self::Ref(id) if matches!(vm.heap.get(*id), HeapData::Instance(_)) => instance_str(*id, vm), @@ -469,7 +491,23 @@ impl<'h> PyTrait<'h> for Value { } } + /// For lists/deques, tries user `__radd__` before native extension from an iterable. + /// A reflected result replaces the value; native extension preserves the container's identity. fn py_iadd_impl(&mut self, other: &Self, vm: &mut VM<'_>) -> RunResult { + // CPython tries numeric addition, including the RHS's `__radd__`, before + // sequence in-place concatenation. A user operand can therefore replace + // the assigned value even if it is iterable; aliases keep the original container. + // Only an absent or declined `__radd__` permits native extension; errors propagate. + let sequence = matches!(self.py_type_heap(vm.heap), Type::List | Type::Deque); + if sequence + && matches!(other.py_type_heap(vm.heap), Type::Instance(_)) + && let Some(result) = other.py_radd_impl(self, vm)? + { + let old = mem::replace(self, result); + old.drop_with(vm); + return Ok(true); + } + if let Self::Ref(id) = self { vm.heap.read(*id).py_iadd_impl(other, vm) } else { @@ -477,6 +515,43 @@ impl<'h> PyTrait<'h> for Value { } } + /// For lists/deques, tries user `__rmul__` before native repetition through `__index__`. + /// A reflected result replaces the value; native repetition preserves the container's identity. + fn py_imul_impl(&mut self, other: &Self, vm: &mut VM<'_>) -> RunResult { + // CPython tries numeric multiplication, including the RHS's `__rmul__`, before + // sequence in-place repetition. A user operand can therefore replace + // the assigned value even if it implements `__index__`; aliases keep the original container. + // Only an absent or declined `__rmul__` permits native repetition; errors propagate. + let sequence = matches!(self.py_type_heap(vm.heap), Type::List | Type::Deque); + if sequence + && matches!(other.py_type_heap(vm.heap), Type::Instance(_)) + && let Some(result) = other.py_rmul_impl(self, vm)? + { + let old = mem::replace(self, result); + old.drop_with(vm); + return Ok(true); + } + + if let Self::Ref(id) = self { + let handled = vm.heap.read(*id).py_imul_impl(other, vm)?; + if !handled && sequence && matches!(other.py_type_heap(vm.heap), Type::Instance(_)) { + // `__rmul__` already declined; binary dispatch would call it a second time. + return Err(ExcType::type_error_sequence_repeat(other.py_type_name(vm))); + } + Ok(handled) + } else { + Ok(false) + } + } + + fn py_ixor_impl(&mut self, other: &Self, vm: &mut VM<'_>) -> RunResult { + if let Self::Ref(id) = self { + vm.heap.read(*id).py_ixor_impl(other, vm) + } else { + Ok(false) + } + } + fn py_isub_impl(&mut self, other: &Self, vm: &mut VM<'_>) -> RunResult { if let Self::Ref(id) = self { vm.heap.read(*id).py_isub_impl(other, vm) @@ -728,7 +803,7 @@ impl<'h> PyTrait<'h> for Value { match self { // Interned string and bytes literals iterate without ever reaching // the heap, so they answer here rather than in `HeapReadOutput`. - Self::InternString(_) | Self::InternBytes(_) => true, + Self::InternString(_) | Self::InlineString(_) | Self::InternBytes(_) => true, Self::Ref(id) => vm.heap.read(*id).py_is_iterable(vm), _ => false, } @@ -740,6 +815,7 @@ impl<'h> PyTrait<'h> for Value { } else { match self { Self::InternString(id) => Ok(CallResult::Value(StringIterator::from_intern(*id, vm))), + Self::InlineString(text) => Ok(CallResult::Value(StringIterator::from_inline(*text, vm))), Self::InternBytes(id) => Ok(CallResult::Value(BytesIterator::from_intern(*id, vm))), _ => Err(ExcType::type_error_not_iterable(&self.py_type_name(vm))), } @@ -827,6 +903,7 @@ impl Value { pub(crate) fn py_value<'h>(&self, vm: &VM<'h>) -> PyValue<'h> { match self { Self::InternString(id) => PyValue::Str(PyStr::Interned(*id)), + Self::InlineString(text) => PyValue::Str(PyStr::Inline(*text)), Self::InternBytes(id) => PyValue::Bytes(PyBytes::Interned(*id)), Self::Int(value) => PyValue::Int(PyInt::Small(*value)), Self::InternLongInt(id) => PyValue::Int(PyInt::Interned(*id)), @@ -847,6 +924,14 @@ impl Value { } } + #[cfg(test)] + pub(crate) fn inline_str(&self) -> Option<&str> { + let Self::InlineString(text) = self else { + return None; + }; + Some(text.as_str()) + } + /// Returns the Python `Type` for this value using only `&Heap` (no full VM borrow). /// /// Wraps [`py_type_shallow`](Self::py_type_shallow) for immediate values and @@ -924,6 +1009,7 @@ impl Value { Self::Int(_) | Self::InternLongInt(_) => Type::Int, Self::Float(_) => Type::Float, Self::InternString(_) => Type::Str, + Self::InlineString(_) => Type::Str, Self::InternBytes(_) => Type::Bytes, Self::Builtin(_) => Type::BuiltinFunction, Self::ModuleFunction(_) | Self::DefFunction(_) => Type::Function, @@ -1092,6 +1178,7 @@ impl Value { // cold arms construct a hasher, via `hash_one`. match self { Self::InternString(string_id) => Ok(Some(vm.interns.str_hash(*string_id))), + Self::InlineString(text) => Ok(Some(hash_python_str(text.as_str()))), Self::InternBytes(bytes_id) => Ok(Some(vm.interns.bytes_hash(*bytes_id))), Self::InternLongInt(long_int_id) => Ok(Some(vm.interns.long_int_hash(*long_int_id))), // Bool and int hash directly as their value, and are equivalent @@ -1112,9 +1199,9 @@ impl Value { Self::None => Ok(Some(hash_named("singleton", "None"))), Self::Builtin(Builtins::Function(function)) => Ok(Some(hash_named("builtin", (*function).into()))), Self::Builtin(Builtins::ExcType(exc_type)) => Ok(Some(hash_named("type", (*exc_type).into()))), - // an instance's class is a heap object, hashed by identity like its instances - Self::Builtin(Builtins::Type(Type::Instance(class_id))) => Ok(Some(identity_hash(*class_id))), - Self::Builtin(Builtins::Type(ty)) => Ok(Some(hash_named("type", &ty.name(vm.heap, vm.interns)))), + Self::Builtin(Builtins::Type(ty)) => { + Ok(Some(hash_named("type", &Type::from(*ty).name(vm.heap, vm.interns)))) + } // the `Debug` form carries the module too, so `time.sleep` and `asyncio.sleep` differ Self::ModuleFunction(function) => Ok(Some(hash_named("module_function", &format!("{function:?}")))), // Hash functions based on function ID @@ -1192,11 +1279,17 @@ impl Value { // `__name__`, class constants and the members handed out as values // all live with the type, including the `AttributeError`. Self::Builtin(Builtins::Type(t)) => { - return match t.class_getattr(attr, vm) { + return match Type::from(*t).class_getattr(attr, vm) { Some(value) => Ok(CallResult::Value(value)), - None => Err(t.attribute_error(attr, vm)), + None => Err(Type::from(*t).attribute_error(attr, vm)), }; } + // A plain `def` has its PEP 649 attributes and nothing else. + Self::DefFunction(func_id) => { + if let Some(result) = annotations::function_getattr(*func_id, None, attr.as_str(vm.interns), vm) { + return result; + } + } _ => {} } let type_name = self.py_type_name(vm); @@ -1431,8 +1524,24 @@ impl Value { ) } - /// Performs Python `*` with reflected-operation fallback. + /// Performs Python `*`, trying the left implementation then the right reflected implementation. + /// Same-class user instances skip the reflected retry. For a builtin sequence on the left + /// and a user instance on the right, `__rmul__` precedes `__index__`-based repetition. + /// Absent or declined methods allow fallback; exceptions propagate immediately. pub(crate) fn py_mul(&self, other: &Self, vm: &mut VM<'_>) -> RunResult { + if matches!(other, Self::Ref(_)) + && matches!(other.py_type_heap(vm.heap), Type::Instance(_)) + && self.py_type_heap(vm.heap).has_sequence_repeat() + { + // Numeric reflected multiplication precedes the sequence's `__index__` conversion. + if let Some(result) = other.py_rmul_impl(self, vm)? { + return Ok(result); + } + return self + .py_mul_impl(other, vm)? + .ok_or_else(|| ExcType::type_error_sequence_repeat(other.py_type_name(vm))); + } + self.binary_op( other, vm, @@ -1690,6 +1799,7 @@ impl Value { Self::ModuleFunction(mf) => Self::ModuleFunction(*mf), Self::DefFunction(f) => Self::DefFunction(*f), Self::InternString(s) => Self::InternString(*s), + Self::InlineString(text) => Self::InlineString(*text), Self::InternBytes(b) => Self::InternBytes(*b), Self::InternLongInt(bi) => Self::InternLongInt(*bi), Self::Marker(m) => Self::Marker(*m), @@ -1757,13 +1867,12 @@ impl Value { } } - /// Converts the value into a keyword string representation if possible. - /// - /// Returns `Some(KeywordStr)` for `InternString` values or heap `str` - /// objects, otherwise returns `None`. + /// Returns a string name that can outlive a heap borrow. + /// Copies heap-backed text; returns `None` for non-string values. pub fn as_either_str(&self, heap: &Heap) -> Option { match self { Self::InternString(id) => Some(EitherStr::Interned(*id)), + Self::InlineString(text) => Some(EitherStr::Inline(*text)), Self::Ref(heap_id) => match heap.get(*heap_id) { HeapData::Str(s) => Some(EitherStr::Heap(s.as_str().to_owned())), _ => None, @@ -1772,42 +1881,46 @@ impl Value { } } - /// Borrows the value as a `&str` if it is a string (interned or heap `str`). - /// - /// Unlike [`as_either_str`](Self::as_either_str) this never allocates — both - /// interned and heap strings are returned by borrow — and it errors rather - /// than returning `None` for non-strings, with CPython's generic `expected - /// string, not ` message. Use it wherever a function reads a `str` - /// argument it does not need to own; the borrow keeps `self` and the heap - /// pinned, so drop/allocate only once it ends. - pub(crate) fn to_str<'a>(&'a self, vm: &'a VM<'_>) -> RunResult<&'a str> { - self.to_str_heap(vm.heap, vm.interns) + /// Borrows string contents without allocating, or returns `None` for non-strings. + pub(crate) fn as_str<'a>(&'a self, vm: &'a VM<'_>) -> Option<&'a str> { + self.as_str_heap(vm.heap, vm.interns) + } + + /// [`as_str`](Self::as_str) for contexts without a `&VM`. + pub(crate) fn as_str_heap<'a>(&'a self, heap: &'a Heap, interns: &'a Interns) -> Option<&'a str> { + match self { + Self::InternString(string_id) => Some(interns.get_str(*string_id)), + Self::InlineString(text) => Some(text.as_str()), + Self::Ref(heap_id) => match heap.get(*heap_id) { + HeapData::Str(s) => Some(s.as_str()), + _ => None, + }, + _ => None, + } + } + + /// Borrows string contents, or raises `TypeError` with `expected string, not `. + pub(crate) fn try_to_str<'a>(&'a self, vm: &'a VM<'_>) -> RunResult<&'a str> { + self.try_to_str_heap(vm.heap, vm.interns) } - /// [`to_str`](Self::to_str) for contexts without a `&VM` — takes `heap` and + /// [`try_to_str`](Self::try_to_str) for contexts without a `&VM` — takes `heap` and /// `interns` separately so callers can keep a disjoint `&mut` borrow of /// another `VM` field alive (e.g. resolving a `str` `Value` produced by /// `py_str` while writing it to `vm.print_writer`). - pub(crate) fn to_str_heap<'a>(&'a self, heap: &'a Heap, interns: &'a Interns) -> RunResult<&'a str> { - match self { - Self::InternString(string_id) => return Ok(interns.get_str(*string_id)), - Self::Ref(heap_id) => { - if let HeapData::Str(s) = heap.get(*heap_id) { - return Ok(s.as_str()); - } - } - _ => {} - } - Err(ExcType::type_error(format!( - "expected string, not {}", - self.py_type_name_heap(heap, interns) - ))) + pub(crate) fn try_to_str_heap<'a>(&'a self, heap: &'a Heap, interns: &'a Interns) -> RunResult<&'a str> { + self.as_str_heap(heap, interns).ok_or_else(|| { + ExcType::type_error(format!( + "expected string, not {}", + self.py_type_name_heap(heap, interns) + )) + }) } /// check if the value is a string. pub fn is_str(&self, heap: &Heap) -> bool { match self { - Self::InternString(_) => true, + Self::InternString(_) | Self::InlineString(_) => true, Self::Ref(heap_id) => matches!(heap.get(*heap_id), HeapData::Str(_)), _ => false, } @@ -1880,10 +1993,11 @@ pub(crate) fn eq_bigint(b: &BigInt, other: &Value, vm: &VM<'_>) -> Option } } -/// `s == other`, resolving the other operand from an interned or heap string. +/// `s == other`, returning `None` for non-string operands. pub(crate) fn eq_str(s: &str, other: &Value, vm: &VM<'_>) -> Option { match other { Value::InternString(id) => Some(s == vm.interns.get_str(*id)), + Value::InlineString(text) => Some(s.as_bytes() == text.as_bytes()), Value::Ref(id) if let HeapData::Str(o) = vm.heap.get(*id) => Some(s == o.as_str()), _ => None, } @@ -1898,14 +2012,13 @@ pub(crate) fn eq_bytes(b: &[u8], other: &Value, vm: &VM<'_>) -> Option { } } -/// Interned or heap-owned string identifier. -/// -/// Used when a string value can come from either the intern table (for known -/// static strings and keywords) or from a heap-allocated Python string object. +/// A string name that can outlive a heap borrow. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub(crate) enum EitherStr { /// Interned string identifier (cheap comparisons and no allocation). Interned(StringId), + /// Short UTF-8 string stored without a heap allocation. + Inline(InlineStr), /// Heap-owned string extracted from a `str` object. Heap(String), } @@ -1924,31 +2037,37 @@ impl From for EitherStr { } impl EitherStr { - /// Returns the keyword as a str slice for error messages or comparisons. + /// Returns an owned string value, preserving interned names. + pub(crate) fn as_value(&self, heap: &Heap) -> Value { + match self { + Self::Interned(id) => Value::InternString(*id), + Self::Inline(text) => Value::InlineString(*text), + Self::Heap(text) => allocate_string(text.as_str(), heap), + } + } + + /// Returns the keyword text for error messages or comparisons. pub fn as_str<'a>(&'a self, interns: &'a Interns) -> &'a str { match self { Self::Interned(id) => interns.get_str(*id), + Self::Inline(text) => text.as_str(), Self::Heap(s) => s.as_str(), } } - /// The text as a `Cow` borrowing only `interns`, so it outlives heap - /// borrows — error messages format the name after `drop_with` cleanup. + /// The text as a `Cow` that outlives heap borrows, for error messages + /// formatted after `drop_with` cleanup. pub fn to_cow<'i>(&self, interns: &'i Interns) -> Cow<'i, str> { match self { Self::Interned(id) => Cow::Borrowed(interns.get_str(*id)), + Self::Inline(text) => Cow::Owned(text.as_str().to_owned()), Self::Heap(s) => Cow::Owned(s.clone()), } } - /// Re-resolves a heap string to its interned id when the interner already - /// knows the text. + /// Re-resolves a runtime string to its interned id when the interner knows it. /// - /// Builtin attribute dispatch matches on `StringId`, so a name computed at - /// runtime (`getattr(x, 'up' + 'per')`) arrives as [`Heap`](Self::Heap) and - /// misses every builtin attribute — while still resolving on instances and - /// modules, which compare by text. Interning is a lookup, never an insert, - /// so sandboxed code cannot grow the interner by guessing names. + /// Looks up existing IDs for builtin attribute dispatch without growing the interner. #[must_use] pub fn resolve_interned(self, interns: &Interns) -> Self { match self { @@ -1956,6 +2075,10 @@ impl EitherStr { Some(id) => Self::Interned(id), None => Self::Heap(s), }, + Self::Inline(text) => match interns.get_string_id_by_name(text.as_str()) { + Some(id) => Self::Interned(id), + None => self, + }, already @ Self::Interned(_) => already, } } @@ -1964,6 +2087,7 @@ impl EitherStr { pub fn matches(&self, target: StringId, interns: &Interns) -> bool { match self { Self::Interned(id) => *id == target, + Self::Inline(text) => text.as_bytes() == interns.get_str(target).as_bytes(), Self::Heap(s) => s == interns.get_str(target), } } @@ -1973,7 +2097,7 @@ impl EitherStr { pub fn string_id(&self) -> Option { match self { Self::Interned(id) => Some(*id), - Self::Heap(_) => None, + Self::Inline(_) | Self::Heap(_) => None, } } @@ -1982,17 +2106,16 @@ impl EitherStr { pub fn static_string(&self, interns: &Interns) -> Option { match self { Self::Interned(id) => interns.static_string(*id), + Self::Inline(text) => StaticStrings::from_str(text.as_str()).ok(), Self::Heap(value) => StaticStrings::from_str(value).ok(), } } - /// Converts this `EitherStr` into an owned `String`. - /// - /// For interned strings, looks up and clones the string content. - /// For heap strings, returns the owned string directly. + /// Returns owned text, reusing an existing `String` when possible. pub fn into_string(self, interns: &Interns) -> String { match self { Self::Interned(id) => interns.get_str(id).to_owned(), + Self::Inline(text) => text.as_str().to_owned(), Self::Heap(s) => s, } } @@ -2039,6 +2162,31 @@ impl Marker { } } + /// Whether this `typing` form is subscriptable (`List[int]`, `ClassVar[int]`), + /// building a [`GenericAlias`](crate::types::GenericAlias); `Optional[X]` + /// builds a union instead, and `Any`, `TypeVar` and the rest are not generic. + pub(crate) fn is_generic_form(self) -> bool { + matches!( + self.0, + StaticStrings::ListType + | StaticStrings::DictType + | StaticStrings::TupleType + | StaticStrings::SetType + | StaticStrings::FrozenSet + | StaticStrings::Callable + | StaticStrings::Type + | StaticStrings::Sequence + | StaticStrings::Mapping + | StaticStrings::Iterable + | StaticStrings::IteratorType + | StaticStrings::Generator + | StaticStrings::ClassVar + | StaticStrings::FinalType + | StaticStrings::Literal + | StaticStrings::Annotated + ) + } + /// Writes the Python repr for this marker. /// /// System markers have special repr formats ("", ""); @@ -2204,9 +2352,53 @@ mod tests { use crate::{ heap::HeapReader, run::{Program, SessionTables}, - types::LongInt, + types::{ + LongInt, + str::{allocate_string_no_interning, allocate_string_on_heap}, + }, }; + #[test] + fn value_size_is_16_bytes() { + assert_eq!(mem::size_of::(), 16); + } + + #[test] + fn inline_string_capacity_is_fifteen_utf8_bytes() { + let mut heap = Heap::new(16, ResourceTracker::default()); + for text in ["123456789012345", "ééééééabc"] { + for value in [ + allocate_string(text.to_owned(), &heap), + allocate_string_no_interning(text.to_owned(), &heap), + ] { + assert!(matches!(value, Value::InlineString(_))); + assert_eq!(value.inline_str(), Some(text)); + value.drop_with(&mut heap); + } + } + for text in ["1234567890123456", "ééééééabcd"] { + for value in [ + allocate_string(text.to_owned(), &heap), + allocate_string_no_interning(text.to_owned(), &heap), + ] { + assert!(matches!(value, Value::Ref(_))); + value.drop_with(&mut heap); + } + } + } + + #[test] + fn inline_string_dump_roundtrip_preserves_every_length() { + for length in 0..=15 { + let text = "a".repeat(length); + let value = Value::InlineString(InlineStr::new(&text).unwrap()); + let dumped = minicbor_serde::to_vec(&value).unwrap(); + let restored: Value = minicbor_serde::from_slice(&dumped).unwrap(); + assert_eq!(restored.inline_str(), Some("a".repeat(length).as_str())); + } + assert_eq!(Value::None.inline_str(), None); + } + /// Creates a heap and directly allocates a LongInt with the given BigInt value. /// /// This bypasses `LongInt::into_value()` which would demote i64-fitting values. @@ -2218,6 +2410,48 @@ mod tests { (heap, heap_id) } + #[test] + fn as_either_str_keeps_inline_text_inline() { + let heap = Heap::new(16, ResourceTracker::default()); + let value = allocate_string("abcdefghijklmno".to_owned(), &heap); + + let name = value.as_either_str(&heap).unwrap(); + assert!(matches!(name, EitherStr::Inline(_))); + assert_eq!(name.as_str(&Interns::default()), "abcdefghijklmno"); + } + + #[test] + fn inline_attribute_names_resolve_without_inserting() { + let mut heap = Heap::new(16, ResourceTracker::default()); + let interns = Interns::default(); + let start = interns.intern_static(StaticStrings::Start); + let value = allocate_string("start".to_owned(), &heap); + let name = value.as_either_str(&heap).unwrap(); + assert!(name.matches(start, &interns)); + assert_eq!(name.string_id(), None); + assert_eq!(name.static_string(&interns), interns.static_string(start)); + assert!(matches!(name.to_cow(&interns), Cow::Owned(text) if text == "start")); + assert!(matches!(name.resolve_interned(&interns), EitherStr::Interned(id) if id == start)); + value.drop_with(&mut heap); + + let value = allocate_string("zzq".to_owned(), &heap); + let name = value.as_either_str(&heap).unwrap().resolve_interned(&interns); + assert!(matches!(name, EitherStr::Inline(_))); + assert!(!name.matches(start, &interns)); + assert_eq!(name.static_string(&interns), None); + assert_eq!(name.into_string(&interns), "zzq"); + assert!(interns.get_string_id_by_name("zzq").is_none()); + value.drop_with(&mut heap); + + for text in ["start", "a_name_longer_than_inline"] { + let value = allocate_string_on_heap(text, &heap); + let name = value.as_either_str(&heap).unwrap().resolve_interned(&interns); + assert_eq!(name.as_str(&interns), text); + assert_eq!(name.string_id(), (text == "start").then_some(start)); + value.drop_with(&mut heap); + } + } + /// Tests that `as_index()` correctly handles a LongInt containing an i64-fitting value. /// /// This tests a defensive code path that's normally unreachable because diff --git a/crates/bashkit-monty/tests/fixtures/builtin_type_serialization.txt b/crates/bashkit-monty/tests/fixtures/builtin_type_serialization.txt new file mode 100755 index 000000000..43e1d8196 --- /dev/null +++ b/crates/bashkit-monty/tests/fixtures/builtin_type_serialization.txt @@ -0,0 +1,105 @@ +Ellipsis 0 +NotImplementedType 1 +Type 2 +NoneType 3 +Bool 4 +Int 5 +Float 6 +Complex 7 +Range 8 +Slice 9 +Date 10 +DateTime 11 +TimeDelta 12 +TimeZone 13 +Str 14 +Bytes 15 +List 16 +Tuple 17 +NamedTuple 18 +Dict 19 +DefaultDict 20 +Counter 21 +DictKeys 22 +DictItems 23 +DictValues 24 +Set 25 +FrozenSet 26 +HostClass 27 +Function 30 +BuiltinFunction 31 +Cell 32 +Iterator 33 +ListIterator 34 +CallableIterator 35 +Coroutine 36 +Module 37 +TextIOWrapper 38 +BufferedReader 39 +BufferedWriter 40 +BufferedRandom 41 +SpecialForm 42 +Path 43 +Property 44 +RePattern 45 +ReMatch 46 +DirEntry 47 +ScandirIterator 48 +WalkGenerator 49 +TupleIterator 50 +StrAsciiIterator 51 +StrIterator 52 +BytesIterator 53 +RangeIterator 54 +DictKeyIterator 55 +DictItemIterator 56 +DictValueIterator 57 +SetIterator 58 +ItertoolsCount 59 +ItertoolsRepeat 60 +DataclassField 61 +Deque 62 +DequeIterator 63 +ItertoolsPairwise 64 +ItertoolsCompress 65 +ItertoolsIslice 66 +ItertoolsChain 67 +ItertoolsCycle 68 +DataclassParams 69 +MissingType 70 +ItertoolsTakeWhile 71 +ItertoolsDropWhile 72 +ItertoolsFilterFalse 73 +ItertoolsStarMap 74 +Object 75 +Time 76 +Partial 77 +ItertoolsAccumulate 78 +ItertoolsBatched 79 +ItertoolsZipLongest 80 +GenericAlias 81 +Union 82 +ItertoolsCombinations 83 +ItertoolsCombinationsWithReplacement 84 +ItertoolsPermutations 85 +ItertoolsProduct 86 +ItertoolsGroupBy 87 +ItertoolsGrouper 88 +ItertoolsTee 89 +ItertoolsTeeDataObject 90 +Random 91 +LruCacheWrapper 92 +HashlibHash 93 +HashlibHashXof 94 +Blake2b 95 +Blake2s 96 +CsvReader 97 +CsvWriter 98 +CsvDictReader 99 +CsvDictWriter 100 +CsvDialect 101 +Decimal 102 +DecimalContext 103 +DecimalSignalDict 104 +DecimalContextManager 105 +ForwardRef 106 diff --git a/crates/bashkit-monty/tests/heap_reader/borrowed.rs b/crates/bashkit-monty/tests/heap_reader/borrowed.rs old mode 100644 new mode 100755 diff --git a/crates/bashkit-monty/tests/unit/format_template.rs b/crates/bashkit-monty/tests/unit/format_template.rs new file mode 100755 index 000000000..a4fd5f823 --- /dev/null +++ b/crates/bashkit-monty/tests/unit/format_template.rs @@ -0,0 +1,28 @@ +use std::{ + hint::spin_loop, + time::{Duration, Instant}, +}; + +use monty_types::{ResourceLimits, ResourceTracker}; + +use super::copy_format_template; +use crate::exception_private::RunError; + +#[test] +fn format_template_copy_checks_an_exhausted_budget() { + let tracker = ResourceTracker::new(ResourceLimits::default().max_feed_duration(Duration::ZERO)); + tracker.on_execution_start(); + let wall = Instant::now(); + while tracker.check_time().is_ok() { + assert!( + wall.elapsed() < Duration::from_secs(10), + "execution clock did not advance" + ); + spin_loop(); + } + tracker.on_execution_stop(); + assert!(matches!( + copy_format_template("{missing}", &tracker), + Err(RunError::UncatchableExc(_)) + )); +} diff --git a/crates/bashkit/src/builtins/python.rs b/crates/bashkit/src/builtins/python.rs index 0819a7790..09ac5343f 100644 --- a/crates/bashkit/src/builtins/python.rs +++ b/crates/bashkit/src/builtins/python.rs @@ -895,8 +895,11 @@ async fn handle_os_call( ret(MontyObject::path(rp(&p).to_string_lossy().to_string())) } F::Scan(a) => handle_scan(&a, &rp(&a.path), fs).await, - // Unknown modules: no host modules are offered. - F::Import(name) => ExtFunctionResult::NotFound(name), + // Unknown modules: no host modules are offered. Monty 1.5 passes the + // import's `search_path` alongside the name for its file-import path; + // bashkit answers from host modules only, so the name is all that is + // needed and every import of an unoffered module still fails here. + F::Import(args) => ExtFunctionResult::NotFound(args.module), other => ExtFunctionResult::Error(MontyException::new( ExcType::OSError, Some(format!("{} not supported in virtual mode", other.name())), diff --git a/crates/bashkit/tests/integration/python_tenant_stress_tests.rs b/crates/bashkit/tests/integration/python_tenant_stress_tests.rs index 8eef08868..2e4d4dff4 100644 --- a/crates/bashkit/tests/integration/python_tenant_stress_tests.rs +++ b/crates/bashkit/tests/integration/python_tenant_stress_tests.rs @@ -224,8 +224,15 @@ async fn huge_single_allocations_are_refused_up_front() { let mut bash = tenant(64, 10_000); let r = bash.exec(&format!("python3 -c \"{code}\"")).await.unwrap(); assert_ne!(r.exit_code, 0, "{code}: stdout {}", r.stdout); + // Both errors are the refusal this test is about, raised before + // anything is allocated. `MemoryError` is the requested size + // measured against the tenant's limit; `OverflowError` is a length + // that is not representable at all, which Monty 1.5 rejects + // earlier still (`'ab' * (2**62)` would be 2**63 bytes). CPython + // raises `OverflowError` there too. Anything else -- a crash, a + // different exception, or success -- is a failure. assert!( - r.stderr.contains("MemoryError"), + r.stderr.contains("MemoryError") || r.stderr.contains("OverflowError"), "{code}: stderr {}", r.stderr ); diff --git a/deny.toml b/deny.toml index 9fa744b67..ebf82eb9b 100644 --- a/deny.toml +++ b/deny.toml @@ -26,7 +26,7 @@ confidence-threshold = 0.8 # Allow specific exceptions exceptions = [ # Blue Oak Model License 1.0.0: permissive (MIT-style, with an explicit - # patent grant), OSI approved. Scoped to the crates Monty 1.4 needs for + # patent grant), OSI approved. Scoped to the crates Monty 1.5 needs for # snapshot serialization (via bashkit-monty) rather than allowed globally. { allow = ["BlueOak-1.0.0"], crate = "minicbor" }, { allow = ["BlueOak-1.0.0"], crate = "minicbor-serde" }, diff --git a/justfile b/justfile index 06ec57308..447a477c7 100644 --- a/justfile +++ b/justfile @@ -70,7 +70,7 @@ regen-capability-parity: check-workflow-parity: python3 scripts/check_workflow_parity.py -# Monty forks differ from upstream 1.4.0 only at `bashkit fork:` markers +# Monty forks differ from upstream 1.5.0 only at `bashkit fork:` markers check-monty-fork: python3 scripts/check_monty_fork.py diff --git a/knowledge/log.md b/knowledge/log.md index 1b0e783f8..b58c7c1cd 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -1,5 +1,9 @@ # Bashkit Knowledge Update Log +## 2026-11-08 + +* **Monty forks re-synced to 1.5.0**: the first re-sync since the forks were created, and what the daily upstream watch went red for. Upstream moved ~9k lines and touched all 14 fork-edited files, so the `bashkit fork:` edits were re-applied by 3-way merge (upstream 1.4.0 / fork / upstream 1.5.0) rather than by hand: 9 conflicts, all in the repr helpers and the `fancy-regex` plumbing. Net drift went *down*. Upstream reached fancy-regex 0.20, so that marked version divergence and the marked `Captures<'_, str>` adaptations in `re_match.rs`/`re_pattern.rs` are gone (1.5.0 replaced `Captures` with span buffers); keeping upstream's new `repr_should_truncate` name let every repr call site return to upstream verbatim, leaving the fork's semantics (a time hit raises, a memory hit truncates) in one helper body. The per-VM memory probe and checkpoint hook merged cleanly: upstream's new `ExecutionClock` work touches different parts of `resource.rs`. Behavior changes taken: `'ab' * (2**62)` now raises `OverflowError` up front instead of reaching the memory meter, and the host import callback receives an `ImportArgs` (module plus search path) where it took a bare name -- bashkit answers `NotFound` on the name, so upstream's new file imports stay out. `cpu-clock`/`nix` came along because features and added dependencies are not markable. See [Dependencies](operations/dependencies.md#monty-forks), [Python Builtin](runtimes/python-builtin.md). + ## 2026-11-07 * **Monty in nightly ASan and soak**: the nightly ASan job ran default features, so the Monty forks (unsafe in the metered allocator and VM) were never sanitized. It now has a `--features python` step (307 integration + 66 lib python tests passed locally under ASan, 81 s), and a new `python-stress-soak` job runs the tenant stress suite 300 rounds in release. See [Python Builtin](runtimes/python-builtin.md). diff --git a/knowledge/operations/dependencies.md b/knowledge/operations/dependencies.md index e818ed303..b60135f18 100644 --- a/knowledge/operations/dependencies.md +++ b/knowledge/operations/dependencies.md @@ -63,14 +63,14 @@ lives there, next to the pin, so it cannot drift away from what it explains. Monty is not taken from crates.io. Upstream 1.x replaced the custom tracker trait with a concrete tracker and per-VM memory accounting with a process-global allocator probe, which breaks bashkit's in-process multi-tenant contract. Bashkit -embeds Monty 1.4.0 as two workspace forks, `bashkit-monty` and +embeds Monty 1.5.0 as two workspace forks, `bashkit-monty` and `bashkit-monty-types` (lib names `monty`/`monty_types`), that add a memory probe and a checkpoint hook. They are published with each release before `bashkit`. Upgrade by re-copying upstream source and re-applying the `bashkit fork:` -edits. See [Python Builtin](../runtimes/python-builtin.md#monty-14-embedding-forks-per-vm-metering-checkpoint-hook). +edits. See [Python Builtin](../runtimes/python-builtin.md#monty-15-embedding-forks-per-vm-metering-checkpoint-hook). `scripts/check_monty_fork.py` (CI lint job, `just check-monty-fork`) diffs both -forks against the SHA-256-pinned upstream 1.4.0 `.crate` files and fails on any +forks against the SHA-256-pinned upstream 1.5.0 `.crate` files and fails on any changed region without a `bashkit fork:` marker in it, in the comment or attribute block attached to it (however long), or up to three lines above it, on fork-only files without a marker header, on upstream files missing from @@ -95,6 +95,39 @@ crates only the forks declare, so upstream security fixes arrive by re-sync: 3. Run `python_fuzz` and the tenant stress soak (`BASHKIT_STRESS_ROUNDS=300`, as nightly runs it) before shipping, as the fork's own regression net. +What the 1.4.0 -> 1.5.0 re-sync (the first one) took, beyond that list: + +- **Re-apply the edits with a 3-way merge, not by hand.** Upstream moved ~9k + lines and touched every one of the 14 fork-edited files. Committing upstream + 1.4.0, the fork, and upstream 1.5.0 as three trees and merging left only 9 + conflicts, all in the repr helpers and the `fancy-regex` plumbing. +- **Prefer upstream's spelling for a renamed item.** 1.5.0 renamed the repr + helper to `repr_should_truncate`; keeping that name let every *call site* go + back to upstream verbatim, so the fork's semantics now live in the one + helper body instead of in a marker at each call. Fewer markers is less to + re-apply next time. +- **A changed region needs its own marker.** The marker window is the comment + block attached to the item, so a second changed region lower in the same + function (there, the two inverted `match` arms) needs a marker of its own. +- **Features and added dependencies are not markable**, so the fork has to + take them: 1.5.0 put upstream's Linux thread-CPU clock behind `cpu-clock`, + which `monty` enables on `monty-types`, pulling in `nix` (already exempt in + `supply-chain/config.toml`). Update the `monty-macros` exemption too -- it is + pinned `=` by upstream and keyed per exact version. +- **Vendor the test files `src/` includes.** `#[cfg(test)]` modules inside + `src/` `#[path]`-include files under `tests/`, and CI's + `cargo test --workspace --lib` builds the fork lib test target even though + `[lib] test = false` excludes it by default. 1.5.0 added two such modules and + an `include_str!` fixture; missing files fail the build, and the `#[cfg(test)]` + code may also need a dev-dependency (`serde_json`). +- **Expect Python-visible behavior to move.** 1.5.0 refuses + `'ab' * (2**62)` with `OverflowError` (CPython's own error for a length that + is not representable) rather than letting it reach the memory meter, so + `huge_single_allocations_are_refused_up_front` accepts either that or + `MemoryError`. 1.5.0 also passes an `ImportArgs` (module plus search path) + where the host import callback took a bare name; bashkit offers host modules + only and answers `NotFound` on the name, which keeps file imports out. + ### A fork dependency may be marked ahead of upstream A dependency's *version* may diverge when the fork's `Cargo.toml` line carries @@ -135,11 +168,14 @@ every such bump unmergeable: #2860 (fancy-regex 0.17 -> 0.20, getrandom 0.3 -> 0.4) is the shape, and it would have come back every week. Holding the fork at upstream's version instead put two majors of fancy-regex in the graph. -`fancy-regex` and `getrandom` are marked today. Taking a shared bump therefore +`getrandom` and `jiter` are marked today. Taking a shared bump therefore means moving the fork line too, marking it, and re-applying whatever source -adaptation the new major needs — fancy-regex 0.20 made `Captures` generic over -the haystack type, so `re_match.rs` and `re_pattern.rs` carry marked -`Captures<'_, str>` edits. Because the `re` module is reachable from untrusted +adaptation the new major needs. `fancy-regex` was marked until the 1.5.0 +re-sync: upstream Monty moved to 0.20 itself, so the fork no longer leads it +and the marker had to go -- a marker on a dependency that matches upstream is +itself an error. Upstream also replaced the `Captures` plumbing in +`re_match.rs`/`re_pattern.rs` with span buffers, which retired the marked +`Captures<'_, str>` adaptation those two files carried. Because the `re` module is reachable from untrusted Python, a major there can move Python-visible behavior: `python_integration_tests::regex_semantics` pins the cases 0.20 changed (`\xHH` above 0x7F matching the codepoint, word-boundary alternation) against @@ -258,7 +294,7 @@ the vendored parser in one deliberate change — not inside an aggregated committed lockfiles (cargo accepts only `auto`/`lockfile-only` as `versioning-strategy`; `increase` made the whole config fail to parse). - Crates only the Monty forks declare are ignored in the "/" entry: the forks - keep Monty 1.4.0's versions until upstream source is re-copied. Shared deps + keep Monty 1.5.0's versions until upstream source is re-copied. Shared deps stay bumpable. `scripts/tests/test_dependabot_coverage.py` enforces all three. diff --git a/knowledge/runtimes/python-builtin.md b/knowledge/runtimes/python-builtin.md index 818e1a7e6..8763693a0 100644 --- a/knowledge/runtimes/python-builtin.md +++ b/knowledge/runtimes/python-builtin.md @@ -107,14 +107,19 @@ capped a default script at ~95 `python3` calls even for `pass`. The parser enforces a nesting-depth limit (200 release / 35 debug) against stack overflow from deeply nested expressions. -### Monty 1.4 embedding: forks, per-VM metering, checkpoint hook +### Monty 1.5 embedding: forks, per-VM metering, checkpoint hook -Bashkit embeds Monty 1.4.0 through two forks in this workspace, published to +Bashkit embeds Monty 1.5.0 through two forks in this workspace, published to crates.io as `bashkit-monty` and `bashkit-monty-types` with each bashkit release (like `bashkit-cpython-wasm`). Their library names stay `monty` and -`monty_types`. Source is upstream 1.4.0 with every local edit marked +`monty_types`. Source is upstream 1.5.0 with every local edit marked `bashkit fork:`; rustfmt and lints are off for them, and upstream tests are not -vendored. Two panic/assert messages in `heap/` also drop the formatted id +vendored -- except the few files a `#[cfg(test)]` module inside `src/` +`#[path]`-includes, which must exist for the lib test target to compile +(`tests/heap_reader/borrowed.rs`, `tests/unit/format_template.rs`, +`tests/fixtures/builtin_type_serialization.txt`, and monty-types' +`tests/unit/execution_clock.rs`). `serde_json` is a fork dev-dependency for +the same reason. Two panic/assert messages in `heap/` also drop the formatted id or uuid, so CodeQL's cleartext-logging rule (a false positive there) stays quiet. Drop the forks once upstream ships equivalent hooks. @@ -189,7 +194,7 @@ time-limit error (exit 124) where upstream truncated to `...[timeout]`; a memory hit still truncates. Pinned by `whitebox_resource_limits::shared_graph_walks_respect_time_limit`. -Known upstream gap in 1.4.0: `str.join` can overshoot `max_memory` before the +Known upstream gap in 1.5.0: `str.join` can overshoot `max_memory` before the next check (bounded by the meter, not by Monty). ### Python Feature Support diff --git a/scripts/check_monty_fork.py b/scripts/check_monty_fork.py index 6a59edb5b..f73dea99a 100755 --- a/scripts/check_monty_fork.py +++ b/scripts/check_monty_fork.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Check that the Monty forks differ from upstream only where marked. -crates/bashkit-monty and crates/bashkit-monty-types are copies of Monty 1.4.0 +crates/bashkit-monty and crates/bashkit-monty-types are copies of Monty 1.5.0 from crates.io with a few local edits, each marked with a `bashkit fork:` comment. This compares every file in the forks with the pinned upstream `.crate` and fails on any changed region that has no marker in or just above @@ -35,16 +35,16 @@ # comment/attribute block attached to the changed item is searched in full on # top of this, however long it is, see `marker_window`. MARKER_WINDOW = 3 -VERSION = '1.4.0' +VERSION = '1.5.0' UPSTREAM = { # fork directory: (crates.io name, sha256 of the .crate) 'bashkit-monty': ( 'monty', - 'b7d354901f6d6655e6bc3826f31c035417025253d7c3f7b3ef1519f681dd3469', + 'cd3e3404a0a11ea8669e30dab21b27462554536b29500b75824582ce850ebbbe', ), 'bashkit-monty-types': ( 'monty-types', - '560e0f529ceb10575efb25dabc95d41e9de0f5036fbb46f02c2ac03d83dc89e3', + '7a6d36dbb6f4f754e5f12ad3040e5c1d0455aee431f46cd48d36cf309e58691a', ), } # Fork-only packaging files, not upstream source. Cargo.toml is not diffed as diff --git a/scripts/tests/test_check_monty_fork.py b/scripts/tests/test_check_monty_fork.py index f8fa7398d..d86c74ac5 100644 --- a/scripts/tests/test_check_monty_fork.py +++ b/scripts/tests/test_check_monty_fork.py @@ -321,7 +321,7 @@ def test_a_marker_does_not_excuse_a_source_substitution(self): def test_a_patch_table_fails(self): # `[patch]` redirects a crate's source without touching the # `[dependencies]` line the per-dep source check reads, so it would - # otherwise slip past. Upstream Monty 1.4 has none. + # otherwise slip past. Upstream Monty 1.5 has none. self.assert_manifest_error( FORK_TOML + '\n[patch.crates-io]\nserde = { git = "https://e.example/s" }\n', '[patch] redirects', diff --git a/scripts/tests/test_dependabot_coverage.py b/scripts/tests/test_dependabot_coverage.py index 0a3fdb2c1..fa11a110f 100644 --- a/scripts/tests/test_dependabot_coverage.py +++ b/scripts/tests/test_dependabot_coverage.py @@ -214,7 +214,7 @@ def test_root_requirements_are_not_prereleases_over_a_stable_lock(self): ) def test_fork_only_deps_are_ignored_by_the_root_entry(self): - # crates/bashkit-monty(-types) are forks of Monty 1.4.0 and keep its + # crates/bashkit-monty(-types) are forks of Monty 1.5.0 and keep its # dependency versions until upstream source is re-copied. Crates only # they declare must not be bumped by Dependabot (#2848 did, and broke # the fork build). Shared ones stay bumpable for bashkit's sake. diff --git a/supply-chain/config.toml b/supply-chain/config.toml index cd694db42..820f6e250 100644 --- a/supply-chain/config.toml +++ b/supply-chain/config.toml @@ -29,12 +29,12 @@ criteria = "safe-to-deploy" [policy.bashkit-monty] audit-as-crates-io = false criteria = "safe-to-deploy" -notes = "In-workspace fork of pydantic/monty 1.4.0; local edits are marked `bashkit fork:`." +notes = "In-workspace fork of pydantic/monty 1.5.0; local edits are marked `bashkit fork:`." [policy.bashkit-monty-types] audit-as-crates-io = false criteria = "safe-to-deploy" -notes = "In-workspace fork of pydantic/monty-types 1.4.0 plus the memory-probe and checkpoint hooks; local edits are marked `bashkit fork:`." +notes = "In-workspace fork of pydantic/monty-types 1.5.0 plus the memory-probe and checkpoint hooks; local edits are marked `bashkit fork:`." [policy.bashkit-python] audit-as-crates-io = false @@ -1315,7 +1315,7 @@ version = "0.2.3" criteria = "safe-to-deploy" [[exemptions.monty-macros]] -version = "1.4.0" +version = "1.5.0" criteria = "safe-to-deploy" [[exemptions.multiversion_no_op]]